最近看自动注入的时候,发现很多的注解都见过,不知道到底是那块解析的。本篇文章将对springboot中的注解进行分析,主要是理清注解的功能,实现逻辑不会很详细分析。
@Configuration
@Configuration,将类作为配置,最主要的就是可以在类中使用@Bean注解,标注在方法上,可以将方法的返回值对象放入的容器中,对象的名称是方法名称。
@Component
此注解主要作用是将标注的类放入的容器,@controller,@service本质一样。
@ComponentScans
见名知意,就是扫描@Component注解的,给定包名,可以将包内的使用@Component注解标注的类放入到容器中。注意,这个注解不能单独使用,需要搭配@Configuration注解。
@PropertySource
这个注解的作用是加载一个属性文件,通常用法是加载属性文件,将属性文件值赋值给bean的属性。
使用方法可以参考使用方法,注意,这个注解不能单独使用,需要搭配@Configuration注解。
@ConfigurationProperties
这个注解通常是用来获取主配置文件的(application.yml或者application.properties)中的属性值,将其赋值给bean属性。
使用方法
以DataSourceProperties为例
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {
private ClassLoader classLoader;
private String name;
private boolean generateUniqueName;
private Class<? extends DataSource> type;
private String driverClassName;
private String url;
private String username;
private String password;
private String jndiName;
。。。
}
配置文件中的属性:
spring:
datasource:
driver-class-name:
url:
password:
username:
前缀+属性名称,如果可以对应上配置文件中的key,就把key对应的value,赋值给bean的属性。这个注解可以单独使用,但你想把这个类放入到容器中,就要搭配@Configuration。注意;这个的搭配和前面两个注解的搭配不一样。@PropertySource,@ComponentScans,如果不和@Configuration注解一起使用,那么其功能就不能实现。而@ConfigurationProperties注解,搭配@Configuration的目的仅仅是将其放入到容器中。如果单独使用功能是可以实现的。 为了方便,springboot还提供了一个注解,EnableConfigurationProperties,这个注解可以将配置的属性bean放入的容器中。
@EnableConfigurationProperties
这个注解可以把属性bean放入到容器中,将处理ConfigurationProperties注解的逻辑类放入到容器中。
使用方法
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcTemplateAutoConfiguration {
原理
直接看EnableConfigurationPropertiesImportSelector
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(EnableConfigurationPropertiesImportSelector.class)
public @interface EnableConfigurationProperties {
org.springframework.boot.context.properties.EnableConfigurationPropertiesImportSelector
实现了ImportSelector接口,直接看selectImports方法
private static final String