Clawdidr
Clawdidr

Reputation: 617

Spring bean in Configuration class not being autowired in a bean defined in .xml file

I have a config class where I create a bean which I'm using in another bean declared in a xml file. When I try to use it from the xml defined bean it throws a NPE because it was never autowired. I have scanned the package where I'm autowiring the config bean but even with that is not taking it.

MyPropertyPlaceholderConfigurer.java

package org.util;

public class MyPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

    @Autowired
    private FileBasedConfigurationBuilder<FileBasedConfiguration> propertiesConfigurationBuilder;

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
        super.processProperties(beanFactoryToProcess, props);
        //breaks due to NPE
        FileBasedConfiguration configuration = propertiesConfigurationBuilder.getConfiguration();
    }
}

applicationContext.xml

    <bean id="myBean" class="org.util.MyPropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <ref bean="appProps" />
            </list>
        </property>
    </bean>

    <context:component-scan base-package="org.util" />

PropertiesFileConfiguration.java

package org.configuration;

@Configuration
public class PropertiesFileConfiguration {
    @Bean
    public FileBasedConfigurationBuilder<FileBasedConfiguration> propertiesConfigurationBuilder() {
        PropertiesBuilderParameters properties = new Parameters().properties();
        properties.setFileName("application.properties");

        FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
                new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class);
        builder.setAutoSave(true);

        return builder.configure(properties);
    }
}

I'm using Spring 4.3.26. NOT using SpringBoot.

Upvotes: 0

Views: 1443

Answers (2)

phonaputer
phonaputer

Reputation: 1530

You could also try specifying the required autowire dependency in your XML instead:

If you add a public setter for propertiesConfigurationBuilder in MyPropertyPlaceholderConfigurer, in your XML you can provide your configuration builder bean as the setter argument for your property placeholder bean like so (ref is the name of your bean, name is the field to set):

<bean id="myBean" class="org.util.MyPropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <ref bean="appProps" />
            </list>
        </property>
        <property name="propertiesConfigurationBuilder" ref="propertiesConfigurationBuilder" />
    </bean>

Upvotes: 1

T.Ahmed
T.Ahmed

Reputation: 15

Try this @ComponentScan(" put Your base package here ") on you config class

Upvotes: 0

Related Questions