Spring @类为prameter的EnableAutoConfiguration注释未初始化属性对象
我有以下@configurationproperties类Spring @类为prameter的EnableAutoConfiguration注释未初始化属性对象,spring,spring-boot,Spring,Spring Boot,我有以下@configurationproperties类 //@Component @ConfigurationProperties @PropertySource("classpath:typesofcharge.properties") public class ChargeProperties { private HashMap<String,String> charge=new HashMap<>(); public HashMap<Str
//@Component
@ConfigurationProperties
@PropertySource("classpath:typesofcharge.properties")
public class ChargeProperties {
private HashMap<String,String> charge=new HashMap<>();
public HashMap<String,String> getCharge()
{
return this.charge;
}
}
如果我在ChargeProperties中使用@Component annotation并在Configuration class中删除ChargeProperties.class注释,则charge HashMap将正确初始化
如果我删除@Component并将ChargeProperties.class作为参数传递,如下所示
@EnableConfigurationPropertiesChargeProperties.class,就像我运行时文档所说的charge HashMap为空一样
我使用的是SpringBoot2.0.2版本,但我遵循的是最新的文档。有人能解释一下为什么这不符合文件的建议吗
属性文件的内容如下
更新属性文件的内容,如图所示
#DO NOT MODIFY THIS FILE
charge.peak=Double_rate;
charge.lateNight=duration_based_charge;
charge.earlyMorning=special_offers;
在@EnableConfigurationProperties注释上指定ChargeProperties.class时,它将通过@EnableConfigurationProperties内的EnableConfigurationPropertieImportSelector类注册为bean
因此,在本例中,如果您仅使用@ConfigurationProperties注释ChargeProperties类,它将创建一个带有空charge HashMap的ChargeProperties bean,因为它默认返回application.properties作为源
可以使用@PropertySource指定自定义源
@PropertySource注释为添加
Spring环境的PropertySource。结合使用
使用@Configuration类
根据上面的文档,要使用@PropertySource加载自定义源,必须使用@Configuration注释
@Configuration
@PropertySource("classpath:typesofcharge.properties")
在引擎盖下,@配置类是一个@组件
所以请回答你的问题。通过在没有@Configuration的情况下指定自定义@PropertySource,spring没有加载@PropertySource注释中的属性,并默认返回到application.properties。如果使用@PropertySource,则必须使用组件,否则将无法读取属性
由于我们添加了@ComponentScan,我们根本不必提及@EnableConfiguationProperties注释。Property类对象可以自动连接为Bean请不要问同样的问题。@M.Deinum我删除了旧问题我的问题是为什么charge HashMap在没有组件注释的情况下不能初始化我认为这是因为@PropertySource需要与@Configuration一起使用。在使用@PropertySourceI时,我修改了我的答案以包含文档。我修改了我的答案以解决您的问题;为什么charge HashMap为空。
@Configuration
@PropertySource("classpath:typesofcharge.properties")
@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
@Component
public @interface Configuration