簡體   English   中英

在Spring上下文中外部注入屬性

[英]Inject properties externally in a Spring context

我的項目有兩個xml文件。 剛加載了第一個文件,實例化了一些bean,調用某些方法為我提供了用戶名和密碼。 該用戶名和密碼必須發送到第二個xml文件,該文件中配置了異步偵聽器。 一旦加載上下文,偵聽器就會啟動。 我想在加載它之前將用戶名和密碼傳遞給該xml。

您可以使用PropertyPlaceholderConfigurer來實現。 假設首先加載springConfigXml1.xml(具有包含以下方法的bean),然后執行setNamePassword方法,然后再加載springConfigXml2.xml(具有AsyncListenerClass):

    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>

但是,隨后將為上下文生活設置用戶名和密碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM