美文网首页
@EnableConfigurationProperties 作

@EnableConfigurationProperties 作

作者: lfboo | 来源:发表于2021-10-25 21:33 被阅读0次

    一句话描述:@EnableConfigurationProperties 把使用 @ConfigurationProperties 的类注入到spring中。

    我们一般用XXXProperties类统一读取property值,避免每次都多次使用@Value

    @ConfigurationProperties(prefix = "test.hello")
    public class HelloProperties {
    
        private String suffix;
    
        public String getSuffix() {
            return suffix;
        }
    
        public void setSuffix(String suffix) {
            this.suffix = suffix;
        }
    }
    

    但仅通过@ConfigurationProperties是无法完成HelloProperties在spring中使用的,如果要想在bean中如下使用,可以通过加@Component或使用@EnableConfigurationProperties

    @Configuration
    public class HelloServiceAutoConfiguration {
    
        @Autowired
        private HelloProperties helloProperties;
    
        @Bean
        public HelloService helloService() {
            HelloService helloService = new HelloService();
            helloService.setHelloProperties(helloProperties);
            return helloService;
        }
    }
    
    使用@Component:

    在HelloProperties上加上@Component

    @Component
    @ConfigurationProperties(prefix = "test.hello")
    public class HelloProperties {
    
        private String suffix;
    
        public String getSuffix() {
            return suffix;
        }
    
        public void setSuffix(String suffix) {
            this.suffix = suffix;
        }
    }
    
    使用@EnableConfigurationProperties:

    在需要引入的地方使用@EnableConfigurationProperties

    @EnableConfigurationProperties(HelloProperties.class)
    @Configuration
    public class HelloServiceAutoConfiguration {
    
        @Autowired
        private HelloProperties helloProperties;
    
        @Bean
        public HelloService helloService() {
            HelloService helloService = new HelloService();
            helloService.setHelloProperties(helloProperties);
            return helloService;
        }
    }
    

    相关文章

      网友评论

          本文标题:@EnableConfigurationProperties 作

          本文链接:https://www.haomeiwen.com/subject/fxgyaltx.html