Spring 中 component-scan 与 annotation-config 的区别

如果在 applicationContext.xml 中启用下述配置,并且在 Dao 或者 Service 的实现类上用了 @Repository 和 @Service,并在 Service 的实现类中 @Autowired 了 Dao 的实现类,会发现,Service 实现类的 Bean 并没有被创建。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

</beans>

搜索资料,官方资料中有对于 annotation-config 的说明 beans-annotation-config,但并没有直接说明 annotation-config 是否只会让部分注解生效,网友对此似乎众说纷纭,此处问题的关键点就在 @Repository 和 @Service 注解是否可以通过 annotation-config 开启。

经过实践,annotation-config 并不能开启 @Repository 和 @Service 等用来定义 Bean 组件的注解 (@Component 及 @Controller 同理也不能开启),需要在 applicationContext.xml 单独配置 Dao 及 Service 的实现类的 Bean。

<bean id="userDao" class="cn.dsscm.dao.UserDaoImpl"></bean>
<bean id="userService" class="cn.dsscm.service.UserServiceImpl"></bean>

至于更详细的原因,参考 * 上的一则提问:difference-between-contextannotation-config-and-contextcomponent-scan,其中有一个答案解释道:

context:annotation-config is used to activate annotations in beans already registered in the application context (no matter if they were defined with XML or by package scanning).
context:component-scan can also do what context:annotation-config does but context:component-scan also scans packages to find and register beans within the application context.

简单来说,使用 annotation-config 可以 “activate annotations”, 但是 “register beans” 似乎只有 component-scan 才可以。

参考资料:

  1. https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-annotation-config
  2. https://blog.csdn.net/u010648555/article/details/76371474
  3. https://*.com/questions/7414794/difference-between-contextannotation-config-and-contextcomponent-scan
上一篇:org.springframework.beans.factory.UnsatisfiedDependencyException找不到mapper


下一篇:【转载】Spring各jar包详解