配置中的属性占位符
使用Spring在xml上下文中,我们可以像这样简单地加载属性:
有没有机会在没有样板的情况下在@Configuration bean(~java代码)中配置相同的属性?
谢谢!
您可以像这样使用注释@PropertySource
@Configuration @PropertySource(value="classpath*:app.properties") public class AppConfig { @Autowired Environment env; @Bean public TestBean testBean() { TestBean testBean = new TestBean(); testBean.setName(env.getProperty("testbean.name")); return testBean; } }
请参阅: http : //static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/context/annotation/PropertySource.html
编辑:如果你使用的是spring引导,你可以使用@ConfigurationProperties
注释将属性文件直接连接到bean属性,如下所示:
test.properties
name=John Doe age=12
PersonProperties.java
@Component @PropertySource("classpath:test.properties") @ConfigurationProperties public class GlobalProperties { private int age; private String name; //getters and setters }
来源: https : //www.mkyong.com/spring-boot/spring-boot-configurationproperties-example/
手动配置可以通过以下代码完成
public static PropertySourcesPlaceholderConfigurer loadProperties(){ PropertySourcesPlaceholderConfigurer propertySPC = new PropertySourcesPlaceholderConfigurer(); Resource[] resources = new ClassPathResource[ ] { new ClassPathResource( "yourfilename.properties" ) }; propertySPC .setLocations( resources ); propertySPC .setIgnoreUnresolvablePlaceholders( true ); return propertySPC ; }
资料来源: 物业占位符
一个简单的解决方案是你的bean还包含一些init函数:
在您的弹簧配置中,您可以提及:
在通过setter设置所有属性后将调用init,在此方法中,您可以覆盖已设置的属性,也可以设置任何属性。