Spring Boot
接口开发常用注解
启动注解@SpringBootApplication
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
}
由源码可以发现:@SpringBootApplication
是一个复合注解,包含了@SpringBootConfiguration
,@EnableAutoConfiguration
和@ComponentScan
@SpringBootConfiguration 注解,继承@Configuration注解,主要用于加载配置文件
@SpringBootConfiguration继承自@Configuration,二者功能也一致,标注当前类是配置类, 并会将当前类内声明的一个或多个以@Bean注解标记的方法的实例纳入到spring容器中,并且实例名就是方法名。
@EnableAutoConfiguration 注解,开启自动配置功能
@EnableAutoConfiguration可以帮助SpringBoot应用将所有符合条件的@Configuration配置都加载到当前SpringBoot创建并使用的IoC容器。借助于Spring框架原有的一个工具类:SpringFactoriesLoader的支持,@EnableAutoConfiguration可以智能的自动配置功效才得以大功告成
@ComponentScan 注解,主要用于组件扫描和自动装配
@ComponentScan的功能其实就是自动扫描并加载符合条件的组件或bean定义,最终将这些bean定义加载到容器中。我们可以通过basePackages等属性指定@ComponentScan自动扫描的范围,如果不指定,则默认Spring框架实现从声明@ComponentScan所在类的package进行扫描,默认情况下是不指定的,所以SpringBoot的启动类最好放在root package下。
Controller
注解
@Controller
标记此类是一个控制器,可以返回视图解析器指定的html页面,通过@ResponseBody
可以将结果返回json、xml数据RestController
相当于@Controller
加@ResponseBody
,实现rest接口开发。返回json数据,不能返回html页面@RequestMapping
定义接口地址,可在标记在类上也可以标记在方法上,支持http的get、post、put等接口@GetMapping
定义get接口,只能标记在方法上,用于查询接口定义,等价于@RequestMapping(method = RequestMethod.GET)
@PostMapping
定义post接口,只能标记在方法上,用于添加记录、复杂条件查询接口,等价于@RequestMapping(method = RequestMethod.POST)
@PutMapping
定义put接口,只能标记在方法上,用于修改接口定义,等价于@RequestMapping(method = RequestMethod.PUT)
@DeleteMapping
定义delete接口,只能标记在方法上,用于删除接口定义,等价于@RequestMapping(method = RequestMethod.DELETE)
@ApiOperation
swagger注解,对接口方法进行说明@Api
swagger注解,对接口类进行说明
参数注解
@RequestBody
定义在方法参数上,用于将json串转成java对象@PathVarible
接收请求路径url中的占位符的值@RequestMapping("/getContent/{uid}") public Content getContent(@PathVariable("cid")Integer id) { System.out.println("cid:"+id); return null; }
@RequestParam
获取请求参数的值@RequestMapping("/getContent") public Content getContent(@RequestParam("cid")Integer id) { System.out.println("cid:"+id); return null; }
Bean注解
@Reposifory
DAO层注解@Service
是@Component
注解的一个特例,作用在类@Scope
作用在类和方法上,用来配置spring bean
的作用域@Component
将普通pojo实例化到spring容器@Autowired
基于类型注入,主要用于构造函数、方法、方法参数、类字段。用于实现Bean的自动注入@Resource
基于名称注入,如果基于名称注入失败则转为基于类型注入