在 xml 上下文中使用 Spring,我们可以像这样简单地加载属性:
<context:property-placeholder location:"classpath*:app.properties"/>
是否有机会在@Configuration bean(〜来自java代码)中配置相同的属性而无需样板?
Thanks!
您可以使用注释@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;
}
}
See: http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/context/annotation/PropertySource.html http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/context/annotation/PropertySource.html
编辑:如果您使用的是 Spring Boot,则可以使用@ConfigurationProperties
注释将属性文件直接连接到 bean 属性,如下所示:
测试.属性
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
}
source:
https://www.mkyong.com/spring-boot/spring-boot-configurationproperties-example/ https://www.mkyong.com/spring-boot/spring-boot-configurationproperties-example/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)