在不使用组件扫描的情况下在Spring中自动注释注释

时间:2010-03-17 02:42:24

标签: spring dependency-injection ioc-container autowired

是否可以使用@Autowired注释自动装配bean而不使用组件扫描?

5 个答案:

答案 0 :(得分:3)

是。 <context-component-scan .. />负责发现使用@Component@Controller@Service@Respository等注释的bean。

为了处理注释(@Autowired@Resource等),您需要<context:annotation-config />。因此,注释在applicationContext.xml

中列出的bean上处理

据我所知,<context-component-scan .. />会自动激活<context:annotation-config />

对于弹簧2.5和3.0都是如此。 (谢谢skaffman)

答案 1 :(得分:0)

我没有试过没有启用组件扫描,但是我可以确认@Autowire注释在Spring 3.0.x中工作,即使是通过XML定义的bean。

答案 2 :(得分:0)

使用AnnotationConfigApplicationContext时,注解配置处理器始终会被注册,这意味着在@ComponentScan级别禁用它们的任何尝试都将被忽略。

答案 3 :(得分:0)

如果在问题中意味着您应该明确声明:
-您的xml文件中的<context:component-scan ...>(启用<context:annotation-config />

-Java配置中的@ComponentScan

那么答案是-是的,可以在代码或xml文件中不使用上述任何语句的情况下启用组件扫描。

另一种方法是使用AnnotationConfigApplicationContext

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

其中“ org.example.your.package”是用于构造型带注释的类的包:@ Component,@ Repository,@ Service等。 AnnotationConfigApplicationContext将在基本包和内部包中搜索您的bean。

答案 4 :(得分:0)

不,如果您使用基于 Java 的配置,我们必须使用 @ComponentScan (或)<context-component-scan .. /> 用于基于 xml 的配置。

注意:如果您不使用任何方法,则不会在 AplicationContext 中创建相应的实例。

当你尝试访问一个资源(http://localhost:8080/customers)时会以

<块引用>

警告:未找到带有 URI [/customers] 的 HTTP 请求的映射 名为“dispatcher

”的 DispatcherServlet
相关问题