自动配置之属性赋值

一:@EnableConfigurationProperties &&ConfigurationProperties

@Configuration
@Conditional()
@EnableConfigurationProperties(XxProperties.class)//将配置参数类组件化
public class XxAutoConfiguration{
    private XxProperties xxProperties;
    
    //@Autowire可用于构造器,此处亦可省略
    public XxAutoConfiguration(XxProperties xxProperties){
        this.xxProperties=xxProperties;
    }
    
    @Bean()
    @Scope()
    @Lazy
    @Conditional()
    public Xx xx(){
        ...
        //这里可使用xxProperties里面封装的从配置文件中取得的参数
        return xx;
    }
    
}

//@Component(可以使用该注解将配置类组件化) vs @EnableConfigurationProperties
@ConfigurationProperties("person")//配置文件中以person开头的配置注入到该类中
class XxProperties{
    private int ss;
    setter/getter
}

//配置文件中参数依据配置参数类编写

二:@PropertySource && @Value

//在任意可注入容器的类上添加
@PropertySource("classpath:xx/xx/xx.properties")
//将配置文件中参数加入到environment
@Value()作用于属性上从environment中取出参数注入到对应的属性上

三 @ConfigurationProperties VS @Value

1、比较

                   @ConfigurationProperties                           @Value
功能批量                 注入配置文件                                  属性单个指定
松散绑定(语法)                支持                                       不支持
spEL                       不支持                                        支持
JSR303校验                   支持                                       不支持
复杂类型                      支持                                       不支持
ps:
    松散语法:javaBean中last-name(或者lastName) -->application.properties中的last-name;
    spEL语法:#{11*2}
    JSR303:@Value会直接忽略,校验规则

2、使用场景分析:
都是从environment中取值注入
如果说,我们只是在某个业务逻辑中获取一下配置文件的某一项值,使用@Value;
如果专门编写了一个javaBean和配置文件进行映射,我们直接使用@ConfigurationProperties

三:底层注解
1.@ComponentScan() //包扫描

@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}

注意:FilterType && TypeFilter
可以实现TypeFilter接口,完成自定义的组件扫描
包扫描:是一个一个从给定包中取出class,并根据TypeFilter 进行过滤添加组件

2.@Import
三种用法

//1.直接添加某个类(全类名)添加组件
@Import({xx.class})
//2.实现ImportSelector接口(返回String[] :要导入的类的全类名)(常用)
@Import({MyImportSelector.class})
//3.实现ImportBeanDefinitionRegistrar接口:直接注册beandefinition
@Import({MyImportBeanDefinitionRegistrar.class})

@EnableAutoConfiguration的底层即为@Import注解
3.@ComponentScan VS @Import

包扫描过滤   VS   导入   (xx.class)(根据导入类的逻辑执行对应的导入(ImportSelector接口,返回String[] :要导入的类的全类名))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容