6

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

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
udit
  • 2,745
  • 3
  • 33
  • 44

5 Answers5

4

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)

alexbt
  • 16,415
  • 6
  • 78
  • 87
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
0

When using AnnotationConfigApplicationContext, annotation config processors are always registered, meaning that any attempt to disable them at the @ComponentScan level would be ignored.

0

If it is meant in the question that you should explicitly state:
- <context:component-scan ...> in your xml file(it enables <context:annotation-config />)
or
- @ComponentScan in your java config

Then the answer is - Yes, it is possible to enable component scanning without any of the stated above statements in your code or xml file.

Another approach is to use AnnotationConfigApplicationContext :

AnnotationConfigApplicationContext context= 
new AnnotationConfigApplicationContext("org.example.your.package");

Where "org.example.your.package" is your package for stereotyped annotated classes: @Component, @Repository, @Service, etc. AnnotationConfigApplicationContext will search for your beans in the base package and inner packages.

Dmitrii Cheremisin
  • 1,498
  • 10
  • 11
0

I have never tried without component-scanning enabled, however I can confirm that @Autowire annotations works in Spring 3.0.x even with beans that are defined via XML.

Eric B.
  • 23,425
  • 50
  • 169
  • 316
0

No, we must use @ComponentScan if you are using java based configuration (or) <context-component-scan .. /> for xml based configuration.

Note: If you are not using any of the approaches no corresponding instances are created in AplicationContext.

and when you try to access a resource (http://localhost:8080/customers) will end up with

WARNING: No mapping found for HTTP request with URI [/customers] in DispatcherServlet with name 'dispatcher

S. Anushan
  • 728
  • 1
  • 6
  • 12