带有 PropertyPlaceholderConfigurer Bean 的 Spring @Configuration文件无法解析@Value注释更新 09/2021
我有以下配置文件:
@Configuration
public class PropertyPlaceholderConfigurerConfig {
@Value("${property:defaultValue}")
private String property;
@Bean
public static PropertyPlaceholderConfigurer ppc() throws IOException {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setLocations(new ClassPathResource("properties/" + property + ".properties"));
ppc.setIgnoreUnresolvablePlaceholders(true);
return ppc;
}
}
我使用以下 VM 选项运行应用程序:
-Dproperty=propertyValue
因此,我希望我的应用程序在启动时加载特定的属性文件。但是由于某种原因,在此阶段不处理注释,并且属性为 。另一方面,如果我通过xml文件进行配置 - 一切都按预期完美地工作。xml 文件示例:@Value
null
PropertyPlaceholderConfigurer
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreResourceNotFound" value="true"/>
<property name="location">
<value>classpath:properties/${property:defaultValue}.properties</value>
</property>
</bean>
如果我尝试在另一个Spring配置文件中注入属性值 - 它被正确注入。如果我将我的bean创建移动到该配置文件 - 字段值再次为空。PropertyPlaceholderConfigurer
作为解决方法,我使用以下代码行:
System.getProperties().getProperty("property", "defaultValue")
这也是有效的,但我想知道为什么会发生这样的行为,也许可以用其他方式重写它,但没有xml?