tonix
tonix

Reputation: 6959

Why Spring doesn't see @Configuration when it loads a bean from applicationContext.xml?

I have the following applicationContext.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">

    <bean class="com.app.config.AppConfig"></bean>      
</beans>

And the following config class:

package com.app.config;

@Configuration
@ComponentScan("com.app")
public class AppConfig {
    // actual beans definition
    @Bean
    ...

    @Bean
    ...

    @Bean
    ...
}

But if I run the app then Spring will not load the AppConfig cause I get NullPointerExceptions on @Autowired dependencies. So it is like Spring doesn't load the JavaConfig @Bean definitions inside the AppConfig class but treats the class as a simple @Component and not a @Configuration component which can in turn contain bean definitions.

Everything works only when I add the <context:component-scan> definition inside the applicationContext.xml instead of the @ComponentScan annotation inside AppConfig, like this:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">

    <bean class="com.app.config.AppConfig"></bean>
    <context:component-scan base-package="com.app" />
</beans>

And AppConfig becomes simply:

package com.app.config;

@Configuration // no more @ComponentScan (it's inside applicationContext.xml)
public class AppConfig {
    // actual beans definition
    @Bean
    ...

    @Bean
    ...

    @Bean
    ...
}

Now, why does Spring doesn't see the @Configuration annotation when it loads the AppConfig bean from applicationContext.xml if applicationContext.xml doesn't have <context:component-scan>?

Upvotes: 0

Views: 2564

Answers (1)

minion
minion

Reputation: 4353

I guess you are missing annotation-config in your xml. Include the below in your appcontext.xml. This is required to process your annotation. Thanks.

<context:annotation-config/>

Upvotes: 4

Related Questions