mercredi 4 mars 2015

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://ift.tt/GArMu6"
xmlns:xsi="http://ift.tt/ra1lAU"
xmlns:context="http://ift.tt/GArMu7"
xsi:schemaLocation="http://ift.tt/GArMu6 http://ift.tt/1jdM0fG
http://ift.tt/GArMu7 http://ift.tt/1tY3uA9">

<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://ift.tt/GArMu6"
xmlns:xsi="http://ift.tt/ra1lAU"
xmlns:context="http://ift.tt/GArMu7"
xsi:schemaLocation="http://ift.tt/GArMu6 http://ift.tt/1jdM0fG
http://ift.tt/GArMu7 http://ift.tt/1tY3uA9">

<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>?


Aucun commentaire:

Enregistrer un commentaire