スタンドアロン アプリケーションがあり、このアプリケーションは値 (プロパティ) を計算してから、Spring コンテキストを開始します。質問は、計算されたプロパティを Spring コンテキストに追加して、プロパティ ファイル ( @Value("${myCalculatedProperty}")
) から読み込まれたプロパティのように使用できるようにするにはどうすればよいかということです。
少し例を挙げると
public static void main(final String[] args) {
String myCalculatedProperty = magicFunction();
AbstractApplicationContext appContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
//How to add myCalculatedProperty to appContext (before starting the context)
appContext.getBean(Process.class).start();
}
アプリケーションコンテキスト.xml:
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:*.properties" />
</bean>
<context:component-scan base-package="com.example.app"/>
これは Spring 3.0 アプリケーションです。
ベストアンサー1
Spring 3.1 では独自のを実装できますPropertySource
。以下を参照してください。Spring 3.1 M1: 統合プロパティ管理。
まず、独自のPropertySource
実装を作成します。
private static class CustomPropertySource extends PropertySource<String> {
public CustomPropertySource() {super("custom");}
@Override
public String getProperty(String name) {
if (name.equals("myCalculatedProperty")) {
return magicFunction(); //you might cache it at will
}
return null;
}
}
PropertySource
アプリケーション コンテキストを更新する前に、以下を追加します。
AbstractApplicationContext appContext =
new ClassPathXmlApplicationContext(
new String[] {"applicationContext.xml"}, false
);
appContext.getEnvironment().getPropertySources().addLast(
new CustomPropertySource()
);
appContext.refresh();
これからは、Spring で新しいプロパティを参照できます。
<context:property-placeholder/>
<bean class="com.example.Process">
<constructor-arg value="${myCalculatedProperty}"/>
</bean>
注釈でも機能します ( を追加することを忘れないでください<context:annotation-config/>
):
@Value("${myCalculatedProperty}")
private String magic;
@PostConstruct
public void init() {
System.out.println("Magic: " + magic);
}