SpringBoot-----@ConfigurationProperties
使用@Value注入每个配置在实际项目中会显得格外麻烦,因为我们的配置通常会是许多个,若是使用@Value注入则需要注入许多次。Spring Boot提供了基于类型安全的配置方式,通过@ConfigurationProperties将properties属性和一个Bean及其属性关联,从而实现类型安全的配置。
通过@Configurationroperties注入配置文件属性需要以下几个步骤,缺一则无法注入。
1.首先需要在待注入的类上添加@ConfigurationProperties(prefix = "XXX")
2.如果注入的属性不在application.properties文件中,而在用户自定义的配置文件中则@PropertySource注解是必须的,@ConfigurationProperties中的location属性被@PropertySource替代。
3.需要注入的属性需要有相应的get set方法。
@Service @PropertySource("classpath:application.properties") @ConfigurationProperties(prefix = "cdm") public class CdmApiServiceImpl implements CdmApiService { String cdmMetaBaseurl; String cdmTemplateBaseUrl; public String getCdmMetaBaseurl() { return cdmMetaBaseurl; } public void setCdmMetaBaseurl(String cdmMetaBaseurl) { this.cdmMetaBaseurl = cdmMetaBaseurl; } public String getCdmTemplateBaseUrl() { return cdmTemplateBaseUrl; } public void setCdmTemplateBaseUrl(String cdmTemplateBaseUrl) { this.cdmTemplateBaseUrl = cdmTemplateBaseUrl; } }
application.properties中的属性与待注入的变量同名(不清楚变量名中是不是可以有下划线,尽量不要使用)
cdm.cdmMetaBaseurl=http://localhost:8181/selfDef/meta cdm.cdmTemplateBaseUrl=http://localhost:8181/selfDef/template
4.在SpringBoot的入口类上加上@EnableConfigurationProperties注解
@SpringBootApplication @EnableConfigurationProperties({CdmApiServiceImpl.class}) public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }

浙公网安备 33010602011771号