Spring application.properties的注入

Overview

Spring提供了如下几种方式读取application.properties的配置:

  • @Value
  • @ConfigurationProperties
    • @Component + @ConfigurationProperties
    • @EnableConfigurationProperties + @ConfigurationProperties

@Value

@Value被Spring用来直接注入配置文件的属性值,有两种情况:

  • 默认从application.properties文件中读取属性值,不需要额外设置。
  • 如果是读取其他文件内容,需要过@PropertySource设置路径信息。

@ConfigurationProperties + @Component

@ConfigurationProperties被Springboot用来将配置文件的属性注入到一个bean对象
(POJO对象,对应于properties文件中的某一类属性)的成员变量中。
@Component用来声明这个POJO为bean,然后再通过@Autowired或者构造器方式将其注入到其他类中来使用。

@ConfigurationProperties + @EnableConfigurationProperties

此种方式是本文重点。它通过@ConfigurationProperties将配置映射到一个POJO对象中,但是不声明@Component.


@ConfigurationProperties(prefix = "demo")
public class DemoProperties{
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

然后在需要用到的地方,用@EnableConfigurationProperties直接声明上述POJO类,来注入对应的配置。

@Configuration
@EnableConfigurationProperties(DemoProperties.class)
public class DemoAutoConfiguration {
    private DemoProperties dp;

    public DemoAutoConfiguration(DemoProperties dp) {
        this.dp = dp;
    }
    ...
}

注意此处用的是构造器注入,也可以用@Autowired的方式注入到指定的成员变量里。

代码链接demo_properties_injection

总结

@EnableConfigurationProperties + @ConfigurationProperties的方式是sprng boot autoconfigure机制中经常用到的方式,需要特别关注!

参考资料

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值