1
votes

with reference to the below example, Autowiring Unmanaged Beans Annotated With @Component It states that you are required to register the bean in xml file and then only you can wire it in your Java class, even though you have used context:component-scan. But the example Difference between context:annotation-config vs context:component-scan [see example with highest up votes (174)] states that you can wire the beans without having its definition in the xml file..

so i got confused which is correct definition ?? I actually tried and got exception as described in the first url (Autowiring unmanaged beans). If we assume that bean definition is required in xml file then what is the real advantage or difference between <context:annotation-config> and <context:component-scan>.

I found both the links contradicting each other

1

1 Answers

2
votes

You can mix and match declaring beans in XML and annotating them with @Component/@Service/@Repository. You can use @Autowired both in beans declared in XML and in beans annotated with @Component/@Service/@Repository. You can use @Autowired to inject beans declared in XML into annotated beans, and to inject annotated beans into beans declared in XML.

<context:annotation-config/> just enables support for dependency injection of managed beans using @Autowired, along with some other features.

http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/beans.html#beans-annotation-config

<context:component-scan ... /> enables everything that <context:annotation-config/> enables, plus, support for @Component/@Service/@Repository, and more. Generally you'll just need to use only <context:component-scan/>.

http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/beans.html#beans-classpath-scanning

"unmanaged" beans are beans that are neither declared in your XML nor annotated and component scanned. You can apparently try to use Spring to inject dependencies into unmanaged beans, using AOP, and <context:spring-configured/>. See the docs here for more info:

http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/aop.html#aop-atconfigurable