8

xmlコンテキストのSpringを使用すると、次のようなプロパティを簡単にロードできます。

<context:property-placeholder location:"classpath*:app.properties"/>

ボイラープレートなしで@ConfigurationBean(Javaコードからの〜)内に同じプロパティを構成する機会はありますか?

ありがとう!

4

3 に答える 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

編集:スプリングブートを使用している場合は、@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/

于 2013-09-05T16:26:54.320 に答える
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 ;
}

出典:プロパティプレースホルダー

于 2013-02-06T08:37:43.557 に答える
0

簡単な解決策の1つは、Beanにいくつかのinit関数も含まれることです。

あなたの春の構成では、あなたはそれについて言及するかもしれません:

<bean id="TestBean" class="path to your class" init-method="init" singleton="false" lazy-init="true" >

initは、すべてのプロパティがセッターを介して設定された後に呼び出されます。このメソッドでは、すでに設定されているプロパティをオーバーライドできます。また、任意のプロパティを設定することもできます。

于 2013-02-06T08:27:36.397 に答える