配置文件中的属性占位符

8
使用Spring在xml上下文中,我们可以像这样简单地加载属性:
<context:property-placeholder location:"classpath*:app.properties"/>

有没有可能在@Configuration bean(从Java代码中)配置相同的属性而无需样板文件?
谢谢!
3个回答

11
您可以像这样使用注释@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 Boot,您可以使用@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
}

source: https://www.mkyong.com/spring-boot/spring-boot-configurationproperties-example/


7
手动配置可以通过以下代码完成
public static PropertySourcesPlaceholderConfigurer loadProperties(){
  PropertySourcesPlaceholderConfigurer propertySPC =
   new PropertySourcesPlaceholderConfigurer();
  Resource[] resources = new ClassPathResource[ ]
   { new ClassPathResource( "yourfilename.properties" ) };
  propertySPC .setLocations( resources );
  propertySPC .setIgnoreUnresolvablePlaceholders( true );
  return propertySPC ;
}

来源:属性占位符

0
一个简单的解决方案是,您的bean也将包含一些初始化函数:
在您的Spring配置中,您可以提到它: <bean id="TestBean" class="path to your class" init-method="init" singleton="false" lazy-init="true" > 在所有属性通过setter设置后,将调用init方法,在此方法中,您可以覆盖已经设置的属性,也可以设置任何属性。

@aim,Dangling Piyush已经为您提供了额外的答案,展示了如何在不使用XML的情况下完成它。 - Michael

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接