Question

I have two xml files for my project. The first file is just loaded, some beans are instantiated and calling some methods gives me a username and password. This username and password has to be sent to the second xml file which has a Asynchronous listener configured in it. As soon as I load the context, the listener starts. I want to pass the username and password which I have to this xml before I load it.

Was it helpful?

Solution

You can acheive this using PropertyPlaceholderConfigurer. Assuming, your springConfigXml1.xml(which has the bean containing the following method) is loaded first and setNamePassword method is executed and then springConfigXml2.xml(which has AsyncListenerClass) is loaded later:

    public void setNamePassword(){
        //some code
        PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
        Properties properties = new Properties();
        properties.setProperty("property.userName", "username");
        properties.setProperty("property.password", "password");
        configurer.setProperties(properties);
                       //Include below line if you have another 
                       //PropertyPlaceholderConfigurer in springConfigXml2.xml       
                        configurer.setIgnoreUnresolvablePlaceholders(true); 
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
        context.addBeanFactoryPostProcessor(configurer);
        context.setConfigLocation("springConfigXml2.xml");
        context.refresh();
        //some code
    }



    springConfigXml2.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
        <bean id="asyncListener" class="com.example.AsyncListenerClass">
            <property name="userName" value="${property.userName}"/>
            <property name="password" value="${property.password}"/>
        </bean>
    </beans>

But then username and password will be set for context life.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top