将参数传递给ApplicationContext

Tap*_*ose 3 java spring applicationcontext

我的应用程序我有一个application-context.xml.现在我将ApplicationContext实例化为:

ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
Run Code Online (Sandbox Code Playgroud)

是否可以通过此实例化传递参数,以便这些参数可用于初始化某些bean的某些属性?

PS:不使用属性文件.由于参数是生成运行时间,如可解决的jar的位置,系统架构,os名称等是可变的.

Joh*_*erg 6

您可以使用PropertyPlaceholderConfigurerapplicationContext.xml

<context:property-placeholder location="classpath:my.properties"/>
Run Code Online (Sandbox Code Playgroud)

这允许您使用语法直接在bean声明中引用属性,${myProperty}假设属性文件包含名为的属性myProperty.

一个示例如何使用这样的属性:

<bean id="foo" class="com.company.Foo">
   <property name="bar" value="${myProperty}"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

另一种替代方案可以基于@Value由其提供的注释SpEL.

  • @TapasBose,这两种方法都支持系统属性,如果这对你有帮助的话 (2认同)

Tap*_*ose 5

以下是我发布的解决方案,可能对将来有所帮助:

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;
    }       
}
Run Code Online (Sandbox Code Playgroud)

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);      
Run Code Online (Sandbox Code Playgroud)

将此bean引用注入application-context.xml的另一个bean:

<bean id="configuration" class="jym.tan.movielibrary.configuration.Configuration" >     
    <property name="runManager" ref="runManager" />
</bean>
Run Code Online (Sandbox Code Playgroud)

谢谢.

  • 这种方法更容易http://forum.springsource.org/showthread.php?71815-Passing-Bean-properties-using-java-util-Properties. (5认同)