在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整合SpringMVC

问题: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>

修改后运行项目进行测试:

Spring整合SpringMVC

问题解决


SpringMVC 中的IOC容器中的bean可以引用 Spring IOC容器中的bean,但是反过来 Spring IOC容器中的bean 不能引用SpringMVC 中的IOC容器中的bean

原因:

Spring整合SpringMVC

相关文章:

  • 2018-11-21
  • 2019-02-20
  • 2021-07-30
  • 2022-01-07
  • 2021-05-01
  • 2021-07-25
  • 2021-10-06
猜你喜欢
  • 2022-01-11
  • 2021-07-30
  • 2022-12-23
  • 2021-08-06
  • 2022-01-01
  • 2020-09-27
  • 2018-09-08
相关资源
相似解决方案