3

私のアプリケーションには、application-context.xml があります。今、私は ApplicationContext を次のようにインスタンス化しています:

ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");

これらのパラメーターを使用して一部の Bean の一部のプロパティを初期化できるように、このインスタンス化を通じてパラメーターを渡すことは可能ですか?

PS: プロパティ ファイルを使用していません。パラメータは実行時に生成されるため、実行可能な jar の場所、システム アーキテクチャ、OS 名などは可変です。

4

2 に答える 2

6

でPropertyPlaceholderConfigurerを使用できますapplicationContext.xml

<context:property-placeholder location="classpath:my.properties"/>

${myProperty}これにより、プロパティファイルに。という名前のプロパティが含まれていると仮定して、構文を使用してBean宣言でプロパティを直接参照できますmyProperty

このようなプロパティの使用方法のサンプル:

<bean id="foo" class="com.company.Foo">
   <property name="bar" value="${myProperty}"/>
</bean>

@Value別の代替案は、によって供給される注釈に基づくことができますSpEL

于 2012-02-22T18:27:49.753 に答える
6

これが解決策です、私はそれを投稿しています、将来誰かに役立つかもしれません:

Bean クラス:

public class RunManager {

    private String jarPath;
    private String osName;
    private String architecture;

    public RunManager() {

    }

    public RunManager(String[] args) {
        this.jarPath = args[0];
        this.osName = args[1];
        this.architecture = args[2];
    }

    public String getJarPath() {
        return jarPath;
    }

    public void setJarPath(String jarPath) {
        this.jarPath = jarPath;
    }

    public String getOsName() {
        return osName;
    }

    public void setOsName(String osName) {
        this.osName = osName;
    }

    public String getArchitecture() {
        return architecture;
    }

    public void setArchitecture(String architecture) {
        this.architecture = architecture;
    }       
}

ApplicationContext の初期化:

DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
BeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(RunManager.class).addConstructorArgValue(args).getBeanDefinition();
beanFactory.registerBeanDefinition("runManager", beanDefinition);
GenericApplicationContext genericApplicationContext = new GenericApplicationContext(beanFactory);
genericApplicationContext.refresh();
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] { "application-context.xml" }, genericApplicationContext);      

application-context.xml の別の Bean へのこの Bean 参照の注入:

<bean id="configuration" class="jym.tan.movielibrary.configuration.Configuration" >     
    <property name="runManager" ref="runManager" />
</bean>

ありがとう。

于 2012-02-22T18:59:01.830 に答える