springboot 常用注解
在spring boot中,摒弃了spring以往项目中大量繁琐的配置,通过自身默认配置,极大的降低了项目搭建的复杂度。在spring boot中,大量注解的使用,使得代码看起来更加简洁,提高开发的效率。这些注解不光包括spring boot自有,也有一些是继承自spring的。
1、@SpringBootApplication
@SpringBootApplication是一个复合注解,包含了@SpringBootConfiguration, @EnableAutoConfiguration, @ComponentScan这三个注解
① @SpringBootConfiguration:标注当前类是配置类,这个注解继承自@Configuration。并会将当前类内声明的一个或多个以@Bean注解标记的方法的实例纳入到srping容器中,并且实例名就是方法名。
② @ComponentScan:扫描当前包及其子包下被@Component,@Controller,@Service,@Repository注解标记的类并纳入到spring容器中进行管理。
③ @EnableAutoConfiguration:是自动配置的注解。
2、@MapperScan
使用@MapperScan可以指定要扫描的Mapper类的包的路径,比如:
@SpringBootApplication
@MapperScan(“com.qf.mapper”)
// 添加对mapper包扫描
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3、@ServletComponentScan
Servlet、Filter、Listener 可以直接通过 @WebServlet、@WebFilter、@WebListener 注解自动注册,这样通过注解servlet ,拦截器,监听器的功能而无需其他配置。(Spring Boot 应用中这三个注解默认是不被扫描的,需要在项目启动类上添加 @ServletComponentScan 注解, 表示对 Servlet 组件扫描。)
4、将类注入到spring容器中
注解 | 说明 |
---|---|
@Repository | 持久层(dao)注入spring容器 |
@Service | 业务逻辑层(server)注入spring容器 |
@Controller | 控制层(controller)注入spring容器 |
@Component | 普通pojo注入spring容器,其他三个注解是这个注解的拓展,并且具有了特定的功能 |
5、@ResponseBody
可以作用在方法上或类上,返回json数据的话,需要配合@ResponseBody注解来完成,表示该方法的返回结果直接写入 HTTP response body 中,而不会被解析为跳转路径,即不会经过视图解析器,返回什么数据即在页面输入什么数据。(@RestController 是@Controller 和@ResponseBody的结合)
6、@RequestMapping、@GetMapping、@PostMapping
这3个注解功能也是类似的,通过这3个注解来映射请求,也就是通过它来指定控制器可以处理哪些URL请求,用在方法上,可以通过配置的url进行访问
注解 | 说明 |
---|---|
@RequestMapping | @RequestMapping(url),通过该注解就可以通过配置的url进行访问,方式可以是get或post请求,两种方式均可 |
@GetMapping | @GetMapping(url) ,功能类似的,只是这个限定了只能是Get请求 |
@PostMapping | @PostMapping(url),功能类似的,只是这个限定了只能是Post请求 |
7、@AutoWired、@Qualifier、@Resource
这3个注解都是基于注解方式进行自动装配,在容器里面将查找到的bean返回,一般@AutoWired用得最多,@Qualifier则需要配合@AutoWired使用,@Resource则是可以通过名字进行自动装配
注解 | 说明 |
---|---|
@AutoWired | @Autowired默认按类型装配,如果发现找到多个bean,则按照name方式比对,如果还有多个,则报出异常 |
@Qualifier | spring的注解,按名字注入 一般当出现两个及以上bean时,不知道要注入哪个,结合@AutoWired使用 |
@Resource | 1. 如果同时指定了name和type,例如@Resource(name = “xxx” type=“xxx”)则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常 2. 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常 3. 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常 4. 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配 |
8、@Value、@ConfigurationProperties、@PropertySource
注解 | 说明 |
---|---|
@Value | 用于获取bean的属性,一般用于读取配置文件的数据,作用在变量上 |
@ConfigurationProperties | 用于注入Bean属性,然后再通过当前Bean获取注入值,作用在类上 |
@PropertySource | 用于指定要读取的配置文件,可以和@Value或@ConfigurationProperties配合使用(不只是yml文件读取) |
9、@RequestParam、@RequestBody、@PathVariable、@RequestHeader、@CookieValue
这3个注解放在一起主要是经常在控制层用来接收参数的。
在后端的同一个接收方法里,@RequestBody与@RequestParam()可以同时使用,但是@RequestBody最多只能有一个,而@RequestParam()可以有多个。
注解 | 说明 |
---|---|
@RequestParam | 获取查询参数。即url?name=这种形式 |
@PathVariable | 获取路径参数。即url/{id}这种形式。 |
@RequestBody | 获取Body的参数,一般用于post获取参数 |
@RequestHeader | 获取请求头的信息 |
@CookieValue | 获取Cookie的信息 |
10、@Transactional: 通过这个注解可以声明事务,可以添加在类上或者方法上。
在spring boot中 不用再单独配置事务管理,一般情况是我们会在servcie层添加了事务注解,即可开启事务。要注意的是,事务的开启只能在public 方法上。
11、@Bean:放在方法的上面,意思是产生一个bean,并交给spring管理
springboot自动配置
我们一般使用SpringApplication.run()来启动整个应用。这个入口类要使用@SpringBootApplication注解声明,它是SpringBoot的核心注解。我们已经知道他是复合注解,这个注解里面,最主要的就是@EnableAutoConfiguration,顾名思义,一看就知道它要开启自动配置,点进去看@EnableAutoConfiguration的源码
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
.....
}
可以看到,在@EnableAutoConfiguration注解内使用到了@import注解来完成导入配置的功能,而EnableAutoConfigurationImportSelector内部则是使用了SpringFactoriesLoader.loadFactoryNames方法进行扫描具有META-INF/spring.factories文件的jar包。下面是1.5.8.RELEASE实现源码:
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return NO_IMPORTS;
}
try {
AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
.loadMetadata(this.beanClassLoader);
AnnotationAttributes attributes = getAttributes(annotationMetadata);
//扫描具有META-INF/spring.factories文件的jar包
List<String> configurations = getCandidateConfigurations(annotationMetadata,
attributes);
//去重
configurations = removeDuplicates(configurations);
//排序
configurations = sort(configurations, autoConfigurationMetadata);
//删除需要排除的类
Set<String> exclusions = getExclusions(annotationMetadata, attributes);
checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
configurations = filter(configurations, autoConfigurationMetadata);
fireAutoConfigurationImportEvents(configurations, exclusions);
return configurations.toArray(new String[configurations.size()]);
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
//加载spring.factories实现
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
Assert.notEmpty(configurations,
"No auto configuration classes found in META-INF/spring.factories. If you "
+ "are using a custom packaging, make sure that file is correct.");
return configurations;
}
扫描具有META-INF/spring.factories文件的jar包,然后把扫描到的这些文件包装成Properties对象,
从properties中获取到EnableAutoConfiguration.class类名对应的值,然后把他们添加在容器中。
以上整个过程就是将类路径下"META-INF/spring.factories"里面配置的所有EnableAutoConfiguration的值加入到容器中。
spring.factories文件是Key=Value形式,多个Value时使用,隔开,该文件中定义了关于初始化,监听器等信息,而真正使自动配置生效的key是org.springframework.boot.autoconfigure.EnableAutoConfiguration,如下所示:
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
//省略......
上面的EnableAutoConfiguration配置了多个类,这些都是Spring Boot中的自动配置相关类;在启动过程中会解析对应类配置信息。每个Configuation类都定义了相关bean的实例化配置。都说明了哪些bean可以被自动配置,什么条件下可以自动配置,并把这些bean实例化出来。如果我们自定义了一个starter的话,也要在该starter的jar包中提供 spring.factories文件,并且为其配置org.springframework.boot.autoconfigure.EnableAutoConfiguration对应的配置类。每一个这样XXAutoConfiguration类都是容器中的一个组件都加入到容器中,用他们来实现自动配置。
springboot其理念是约定优于配置,尽可能地进行自动配置,减少了用户需要动手写的各种冗余配置项,Spring Boot提倡无XML配置文件的理念,使用Spring Boot生成的应用完全不会生成任何配置代码与XML配置文件
SpringBoot的自动配置原理,跟餐厅的机制很类似,如果将SpringBoot比喻成餐厅,把吃饭比做我们的应用,我们来到餐厅吃饭的时候(相当于在应用中加入了@SpringBootApplication),服务员会引导我们开始在菜单点餐纸上点餐(菜单点餐纸是预先定义好的,就相当于spring.factories文件,预先定义了我们可以使用的自动配置信息),餐厅既可以自行搭配烤鱼口味,也可以直接点店家为我们搭配好的口味(springboot也是如此,比如消息中间件,就有好多种口味可以选,比如rabbitmq,kafka,根据业务场景而定),我们在喜欢的菜上进行勾选(相当于在pom文件中引入所需框架的starter),然后确定下单(启动springboot应用)。比如自己想吃花菜,可惜餐厅没有这道辅菜,但是我们可以自己准备然后带过去啊,烤鱼上了就加进去煮(**这就是加入自定义的自动配置了)。