Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autowire Annotation in Spring without using Component Scanning

Is it possible to autowire beans using the @Autowired annotation without using component scanning?

like image 329
udit Avatar asked Mar 17 '10 02:03

udit


People also ask

Can @autowired work without @component?

So the answer is: No, @Autowired does not necessarily mean you must also use @Component . It may be registered with applicationContext. xml or @Configuration+@Bean .

Can we Autowire a non Component class?

Thanks. I am sure you cannot Autowire beans which are not managed by Spring.. You need to get hold of the reference of an instance of XYZ by some other mean. If it is a Helper class make the methods of XYZ static and use them using the class name.

Do we need component scan in Spring boot?

With Spring, we use the @ComponentScan annotation along with the @Configuration annotation to specify the packages that we want to be scanned. @ComponentScan without arguments tells Spring to scan the current package and all of its sub-packages.


1 Answers

Yes. <context-component-scan .. /> is responsible for discovering beans annotated with @Component, @Controller, @Service, @Respository, etc.

In order to have annotations processed (@Autowired, @Resource, etc) you need <context:annotation-config />. Thus annotations are processed on beans that are listed in applicationContext.xml.

As far as I know, <context-component-scan .. /> activates <context:annotation-config /> automatically.

This is true for both spring 2.5 and 3.0. (thanks skaffman)

like image 196
Bozho Avatar answered Oct 18 '22 01:10

Bozho