xmlコンテキストのSpringを使用すると、次のようなプロパティを簡単にロードできます。
<context:property-placeholder location:"classpath*:app.properties"/>
ボイラープレートなしで@ConfigurationBean(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;
}
}
編集:スプリングブートを使用している場合は、@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
}
ソース: 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 ;
}
簡単な解決策の1つは、Beanにいくつかのinit関数も含まれることです。
あなたの春の構成では、あなたはそれについて言及するかもしれません:
<bean id="TestBean" class="path to your class" init-method="init" singleton="false" lazy-init="true" >
initは、すべてのプロパティがセッターを介して設定された後に呼び出されます。このメソッドでは、すでに設定されているプロパティをオーバーライドできます。また、任意のプロパティを設定することもできます。