4

親のコンテキストでは、次のようにプロパティ宣言があります。

<bean id="my.properties"
        class="com.rcslabs.webcall.server.property.PropertyPaceholderConfigurer">
        <property name="locations" value="classpath:/my.properties"/>
</bean>

その後、実行時に子コンテキストを作成し、それらのプロパティを実行時データでオーバーライドする必要があります。それを行うための最良の方法は何ですか?

添加:

より正確には、次のように実行時に手動で子コンテキストを作成しています。

ClassPathXmlApplicationContext childAppContext = new ClassPathXmlApplicationContext(parentApplicationContext);

それで、通常BeanDefinitionRegistryで行われるように、childAppContextでBeanを宣言できますか?

4

2 に答える 2

1

PropertyPlaceholderConfigurerのサブクラスがあるようですが、resolvePropertyランタイム値のロジックチェックでオーバーライドし、それ以外の場合はデフォルトにフォールバックしてみませんか?子コンテキスト専用のサブクラスを作成し、それにランタイム値ソースを挿入する必要がある場合があります。

また、実行時の値をシステムプロパティに配置し、のオーバーライドモードを使用することもできますsystemPropertiesMode。これは単純ですが、それほどクリーンなソリューションではありません。私の最初のアプローチのいくつかのバリエーションの方が良いでしょう。複数のクライアントコンテキストを作成する場合、それらを並行して生成しない限り、これは機能します。

更新:私は次のようなものから始めます:

final Map<String,String> myRuntimeValues;

ClassPathXmlApplicationContext childAppContext = new ClassPathXmlApplicationContext(parentApplicationContext) {
  protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    super.prepareBeanFactory();
    beanFactory.registerSingleton("myRuntimeValues", myRuntimeValues);
  }
};

クライアントコンテキストファイルで定義されたPropertyPlaceholderConfigurerBeanに「myRuntimeValues」を挿入します。もう少し掘り下げると、より良い解決策が得られる可能性があります。これは一般的な使用例ではありません。さらに進んでいくと確信しています。

于 2012-01-12T12:19:59.510 に答える
0

mrembiszの答えを詳しく説明すると、子xml内にBeanをハードコーディングせずに、プロパティをSpringコンテキストに動的に挿入し、親コンテキストからBean参照を渡す完全な例を次に示します。以下のソリューションでは、この目的のために親コンテキストを定義する必要はありません。

public static void main(String args[]) {
    AbstractApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] { "classpath:spring-beans.xml" }) {
        protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            super.prepareBeanFactory(beanFactory);
            ArrayList<Properties> prList = new ArrayList<Properties>();
            Properties pr = new Properties();
            pr.setProperty("name", "MyName");
            prList.add(pr);
            Properties prArray[] = new Properties[prList.size()];
            PropertySourcesPlaceholderConfigurer pConfig = new PropertySourcesPlaceholderConfigurer();
            pConfig.setPropertiesArray(prList.toArray(prArray));
            beanFactory.registerSingleton("pConfig", pConfig);
        }
    };
    appContext.refresh();
    System.out.println(appContext.getBean("name"));
}
于 2013-09-13T07:52:10.957 に答える