Pass Parameter to ApplicationContext

12,195

Solution 1

Here is the solution, I am posting it, might be helpful to someone in future:

The Bean class:

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;
    }       
}

The initialization of the 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);      

The injection of this bean reference to another bean of application-context.xml:

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

Thanks.

Solution 2

You can use the PropertyPlaceholderConfigurer in your applicationContext.xml

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

This allows you to reference properties directly in your bean declarations using syntax ${myProperty} assuming the properties file contains a property named myProperty.

A sample how you can use such a property:

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

Another alternative could be based on the @Value annotation powered by SpEL.

Share:
12,195
Tapas Bose
Author by

Tapas Bose

Java developer.

Updated on July 21, 2022

Comments

  • Tapas Bose
    Tapas Bose almost 2 years

    I my application I have an application-context.xml. Now I am instantiating The ApplicationContext as:

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

    Is it possible to pass parameter through this instantiation so that those parameters could be used to initialize some properties of some beans?

    PS: Not using property file. As the parameters are generated run time, like exicutable jar's location, system architecture, os name etc which is variable.