一、常用注解作用
1.@ConfigurationProperties:读取配置文件的信息,自动封装成实体类
public @interface ConfigurationProperties {
@AliasFor("prefix")
String value() default "";
//文件前缀
@AliasFor("value")
String prefix() default "";
boolean ignoreInvalidFields() default false;
//r如果为false,告诉Spring Boot在有属性不能匹配到声明的域的时候抛出异常
boolean ignoreUnknownFields() default true;
}
2.@EnableConfigurationProperties :让使用 @ConfigurationProperties 注解的类生效。
如果一个配置类只配置@ConfigurationProperties注解,而没有使用@Component,那么在IOC容器中是获取不到properties 配置文件转化的bean。所以 @EnableConfigurationProperties 相当于把使用 @ConfigurationProperties 的类进行了一次注入。
public @interface EnableConfigurationProperties {
/**
* The bean name of the configuration properties validator.
* @since 2.2.0
*/
String VALIDATOR_BEAN_NAME = "configurationPropertiesValidator";
/**
* Convenient way to quickly register
* {@link ConfigurationProperties @ConfigurationProperties} annotated beans with
* Spring. Standard Spring Beans will also be scanned regardless of this value.
* @return {@code @ConfigurationProperties} annotated beans to register
*/
Class<?>[] value() default {};
}
3.@ConditionalOnClass :当给定的在bean存在时,则实例化当前Bean
public @interface ConditionalOnClass {
/**
* The classes that must be present. Since this annotation is parsed by loading class
* bytecode, it is safe to specify classes here that may ultimately not be on the
* classpath, only if this annotation is directly on the affected component and
* <b>not</b> if this annotation is used as a composed, meta-annotation. In order to
* use this annotation as a meta-annotation, only use the {@link #name} attribute.
* @return the classes that must be present
*/
Class<?>[] value() default {};
/**
* The classes names that must be present.
* @return the class names that must be present.
*/
String[] name() default {};
}
4.@ConditionalOnMissingBean :当给定的在bean不存在时,则实例化当前Bean
5.@ConditionalOnClass(KafkaTemplate.class):当给定的类名在类路径上存在,则实例化当前Bean
通俗的说就是Spring工程中引用了Kafka的包 才会构建这个bean
public @interface ConditionalOnClass {
/**
* The classes that must be present. Since this annotation is parsed by loading class
* bytecode, it is safe to specify classes here that may ultimately not be on the
* classpath, only if this annotation is directly on the affected component and
* <b>not</b> if this annotation is used as a composed, meta-annotation. In order to
* use this annotation as a meta-annotation, only use the {@link #name} attribute.
* @return the classes that must be present
*/
Class<?>[] value() default {};
/**
* The classes names that must be present.
* @return the class names that must be present.
*/
String[] name() default {};
}
6.@ConditionalOnMissingClass:当给定的类名在类路径上不存在,则实例化当前Bean
7.@Primary:优先注入
8.@Value用法
① ${ property : default_value }
② #{ obj.property? :default_value }
第一个注入的是外部配置文件对应的property或者yml,第二个则是SpEL表达式对应的内容。
default_value,就是前面的值为空时的默认值
9.@PostConstruct:修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。@PostConstruct在构造函数之后执行,init()方法之前执行
@Constructor > @Autowired > @PostConstruct