问题描述
Spring+SpringMVC启动后警告同一个bean注入了两次
原因分析
Sping+SpringMVC的框架中,IoC容器的加载过程:
- 基本上Web容器(如Tomcat)先加载ContextLoaderListener,然后生成一个IoC容器。
- 然后再实例化DispatchServlet时候会加载对应的配置文件,再次生成Controller相关的IoC容器。
关于上面两个容器关系:
ContextLoaderListener中创建ApplicationContext主要用于整个Web应用程序需要共享的一些组件,比如DAO,数据库的ConnectionFactory等。而由DispatcherServlet创建的ApplicationContext主要用于和该Servlet相关的一些组件,比如Controller、ViewResovler等。
对于作用范围而言,在DispatcherServlet中可以引用由ContextLoaderListener所创建的ApplicationContext,而反过来不行。
于是,如果对于这两份配置没有很好的认识,就会发生重复加载配置文件,导致bean被上述两个IoC容器重复加载。
参考:《相同Bean分别被Spring MVC子容器与Spring父容器初始化,导致@Value注入失败》
解决
方法1. 通过在dispatcher-servlet.xml(applicationContext.xml)中配置exclude-filter来避免重复加载的问题
<context:component-scan base-package="com.maijia.mq">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
方法2. 分开扫描,养成良好习惯:
- applicationContext.xml <context:component-scan base-package="xx.xxx.xx.dao,xx.xx.xxx.service"/>
- dispatcher-servlet.xml <context:component-scan base-package="xx.xx.xx.controller" />