配置中的属性占位符 [英] Property placeholder from Configuration
问题描述
使用Spring在xml上下文中,我们可以简单地加载如下属性:
With Spring in xml context we can simple load properties like this:
<context:property-placeholder location:"classpath*:app.properties"/>
是否有机会在没有样板的情况下在@Configuration bean(〜来自java代码)中配置相同的属性?
Is there any chance to configure same properties inside @Configuration bean (~ from java code) without boilerplate?
谢谢!
推荐答案
您可以使用注释 @PropertySource
喜欢这个
You can use the annotation @PropertySource
like this
@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;
}
}
编辑:如果你使用弹簧靴你可以使用 @ConfigurationProperties
注释将属性文件直接连接到bean属性,如下所示:
if you are using spring boot you can use @ConfigurationProperties
annotation to wire the properties file directly to bean properties, like this:
test.properties
test.properties
name=John Doe
age=12
PersonProperties.java
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 /
这篇关于配置中的属性占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!