解决Spring整合SpringMVC时,Bean被实例化两次的问题

什么都不说,先直接上代码

SpringMVC的包扫描

<context:component-scan base-package="com.voidpawm.springmvc"/>

Spring的包扫描

<context:component-scan base-package="com.voidpawm.springmvc"/>
package com.voidpawm.springmvc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private HelloWorld helloWorld;

    public UserService() {
        System.out.println("UserService Constructor...");
    }

}
package com.voidpawm.springmvc;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloWorld {

    public HelloWorld() {
        System.out.println("HelloWorld Constructor...");
    }

    @RequestMapping("/helloworld")
    public String hello(){
        System.out.println("success");
        //System.out.println(userService);
        return "success";
    }

}

开始运行,看控制台

解决Spring整合SpringMVC时,Bean被实例化两次的问题_第1张图片

HelloWorld和UserService 的构造方法都被实例化了两次

解决方法

  1. 使 Spring 的 IOC 容器扫描的包和 SpringMVC 的 IOC 容器扫描的包没有重合的部分.
  2. 使用 exclude-filter 和 include-filter 子节点来规定扫描的注解

SpringMVC的包扫描配置


    <context:component-scan base-package="com.lbx.*" 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>

use-default-filters=”false”不使用默认的扫描

Spring的包扫描配置

    
    <context:component-scan base-package="com.lbx.*">
        <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)