开发者

Autowire Annotation in Spring without using Component Scanning

开发者 https://www.devze.com 2022-12-23 07:54 出处:网络
Is it possible to autowire beans using th开发者_如何学Ce @Autowired annotation without using component scanning? Yes. <context-component-scan .. /> is responsible for discovering beans annotated

Is it possible to autowire beans using th开发者_如何学Ce @Autowired annotation without using component scanning?


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)


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.


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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消