使用Spring在xml上下文中,我们可以像这样简单地加载属性:
<context:property-placeholder location:"classpath*:app.properties"/>
Run Code Online (Sandbox Code Playgroud)
有没有机会在没有样板的情况下在@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;
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅: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
Run Code Online (Sandbox Code Playgroud)
PersonProperties.java
@Component
@PropertySource("classpath:test.properties")
@ConfigurationProperties
public class GlobalProperties {
private int age;
private String name;
//getters and setters
}
Run Code Online (Sandbox Code Playgroud)
来源: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 ;
}
Run Code Online (Sandbox Code Playgroud)
资料来源:物业占位符
| 归档时间: |
|
| 查看次数: |
8094 次 |
| 最近记录: |