Spring和Spring MVC容器分开包扫描

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chenbetter1996/article/details/86659051

1. Spring MVC容器

一般来说,Spring MVC主要负责的是Controller层,所有可以简单的把配置文件写为

<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd 
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 解决@Controller的前提配置 -->
    <mvc:annotation-driven/>
    <!-- 包扫描,将注解的类注入(扫描Controller层) -->
    <context:component-scan base-package="xyz.cglzwz.controller"/>
</beans>

2. Spring 容器

作为父容器,Spring容器管理其余层,如Service, Domain, Dao等等

<?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
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 包扫描,将注解的类注入 -->
    <context:component-scan base-package="xyz.cglzwz.*">
        <!-- 不扫描@Controller注解 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

</beans>

使用<context:component-scan>的两个子标签可以很好的解决重复扫描的问题

  1. <context:exclude-filter>不扫描
  2. <context:include-filter>加入扫描

当然使用多个包扫描也可以,逗号分割,但是多的话很不雅观。如下

<context:component-scan base-package="xyz.cglzwz.service, xyz.cglzwz.dao, xyz.cglzwz.domain"/>

猜你喜欢

转载自blog.csdn.net/chenbetter1996/article/details/86659051