在 xml 上下文中使用 Spring,我们可以像这样简单地加载属性:
<context:property-placeholder location:"classpath*:app.properties"/>
是否有机会在没有样板的情况下在 @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;
}
}
编辑:如果您使用的是 spring boot,则可以使用 @ConfigurationProperties
注释将属性文件直接连接到 bean 属性,如下所示:
测试.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/
关于java - 配置中的属性占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14724512/