在web-xml中配置Spring IOC容器的Listener
<!-- 配置Spring IOC容器的Listener -->
<!-- needed for ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value>
</context-param>
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
写了两个简单的类进行测试
package cn.it.controller;
import org.springframework.stereotype.Service;
@Service
public class UserService {
public UserService() {
System.out.println("UserService创建");
}
}
package cn.it.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller
public class MyController {
@Autowired
private UserService service;
public MyController() {
// TODO Auto-generated constructor stub
System.out.println("MyController创建");
}
}
启动项目控制台的打印:
问题:Spring IOC容器与SpringMVC IOC容器扫描的包邮重合的部分,就会导致有的bean会被创建两次。
解决办法:
1.使Spring IOC容器扫描的包跟SpringMVC IOC容器扫描的包没有重合的部分(在项目开发中不容易做到)
2.使用exclude-filter和include-filter子节点来规定只能扫描的注解
SpringMVC 的配置文件:
<!-- SpringMVC 只扫描Controller和ControllerAdvice -->
<context:component-scan base-package="cn.it" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
Spring 的配置文件:
<!-- Spring不扫描Controller和 ControllerAdvice-->
<context:component-scan base-package="cn.it">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
修改后运行项目进行测试:
问题解决
SpringMVC 中的IOC容器中的bean可以引用 Spring IOC容器中的bean,但是反过来 Spring IOC容器中的bean 不能引用SpringMVC 中的IOC容器中的bean
原因: