spring注解注入:<context:component-scan>详解

  在Spring MVC中的配置中会遇到<context:include-filter>和 <context:exclude-filter>这两个标签,作为<context:component-scan>的子标签出现。

但在使用时要注意以下几点:

1.在很多配置中一般都会吧ApplicationContext.xml和ApplicationContext-mvc.xml进行分开配置,这种配置显得特别清晰,各司其职。

在ApplicationContext-mvc.xml中只对@Controller进行扫描就可,作为一个控制器,其他的事情不做。

在ApplicationContext.xml中只对一些事务逻辑的注解扫描。

2.现在给定一个项目包的机构:

com.mymelody.controlller

com.mymelody.service

就先给定这两个包机构

(1)在ApplicationContext-mvc.xml中有以下配置:

<!-- 扫描@Controller注解 -->
<context:component-scan base-package="com.mymelody.controller">
    <context:include-filter type="annotation"
        expression="org.springframework.stereotype.Controller" />
</context:component-scan>

  这里要把最终的包写上,而不能这样写base-package=”com.mymelody”。这种写法对于include-filter来讲它都会扫描,而不是仅仅扫描@Controller,这点需要注意。他一般会导致一个常见的错误,那就是事务不起作用,补救的方法是添加use-default-filters=”false”。

(2)在ApplicationContext.xml中有如下配置:

<!-- 配置扫描注解,不扫描@Controller注解 -->
<context:component-scan base-package="com.mymelody">
    <context:exclude-filter type="annotation"
        expression="org.springframework.stereotype.Controller" />
</context:component-scan>

可以看到,他是要扫描com.mymelody包下的所有子类,不包含@Controller。对于exculude-filter不存在包不精确后都进行扫描的问题。

原文地址:https://www.cnblogs.com/mymelody/p/5516860.html