@EnableConfigurationProperties 作

2021-10-25  本文已影响0人  lfboo

一句话描述:@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;
    }
}
上一篇下一篇

猜你喜欢

热点阅读