简体   繁体   中英

Use Spring XML configured bean inside @Configuration Class and Use the bean as factory-bean for another bean

I have below bean configuration in Spring XML that reads some property files. Then I use the bean serverPropertyLoader as factory-bean to create another bean serverProperties of type java.util.Properties by factory-method. I pass the bean serverProperties to org.springframework.context.support.PropertySourcesPlaceholderConfigurer in the next configuration to allow spring handle the property injection.

<bean name="serverPropertyLoader" class="com.xxx.utils.ServerPropertyLoader">
    <constructor-arg name="propertyFiles">
        <list>
            <value>config.properties</value>
        </list>
    </constructor-arg>
</bean>

<bean id="serverProperties" factory-bean="serverPropertyLoader" factory-method="getProperties" />

<bean id="propertyPlaceholder" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
    <property name="propertiesArray">
        <list>
            <ref bean="serverProperties" />
            <ref bean="databaseProperties" /> <!-- Another Type of Properties -->
        </list>
    </property>
</bean>

Now I want to use either serverPropertyLoader or serverProperties inside Spring Java Configuration to read some property while creating a bean as below.

@Configuration
public class DataAccessConf {

    @Autowired
    private ServerPropertyLoader serverPropertyLoader;

    @Autowired
    private Properties serverProperties;

    @Bean(name = "dataSource")
    public javax.sql.DataSource datasource() {

        // want to use serverPropertyLoader or serverProperties here

        return new DataSource(...);
    }
}

Both serverPropertyLoader and serverProperties are null. How can I autowire one of them. Spring Version: 4.1.6.RELEASE

Spring does not know, that bean 'dataSource' needs 'serverProperties' and 'serverPropertyLoader'. So it tries to create 'dataSource' before the other both are autowired in. This is not what one would expect, but I faced similar situations,

Change the signature of datasource to

public javax.sql.DataSource datasource(
       ServerPropertyLoader serverPropertyLoader,
       Properties serverProperties )

Spring will path the parameters , use the parameters instead of the fields, that should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM