Spring与SpringMVC父子容器

xiaoxiao2021-02-28  22

很久以前看到过遇到过有关于Spring和SpringMVC父子容器的问题,最近正好有空,就进行一波探究!

在Spring整体框架的核心概念中,容器是核心思想,就是用来管理Bean的整个生命周期的,而在一个项目中,容器不一定只有一个,Spring中可以包括多个容器,而且容器有上下层关系,目前最常见的一种场景就是在一个项目中引入Spring和SpringMVC这两个框架,那么它其实就是两个容器,Spring是父容器,SpringMVC是其子容器,并且在Spring父容器中注册的Bean对于SpringMVC容器中是可见的,而在SpringMVC容器中注册的Bean对于Spring父容器中是不可见的,也就是子容器可以看见父容器中的注册的Bean,反之就不行,这就可能造成事务失效或者其他问题。

1.关于父子容器的问题,我们得先谈谈<context:component-scan base-package="xx">配置的作用:

该配置的作用主要是扫描xx包以及其子包下所有包含@Component或者其子注解如(@Controller @Service @Repository:Spring注解作用介绍的java类注册为Bean,并加载到容器当中!该标签有个默认属性use-default-filter其缺省值为true(默认加载所有有注解的java类并且注册为bean)那么会对base-package包或者子包下的所有的进行java类进行扫描,并把匹配的java类注册成bean,这样就存在一个问题,注解java类均被Spring父子容器加载,但是实际上,SpringMVC的容器只要加载Controller类,而把Service和其他注解类均交给Spring容器加载,为了避免父子容器重复加载的情况,建议使用如下的配置:

1-1)SpringMVC.xml(子容器):

<context:component-scan base-package="xx.xx.controller"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> 1-2)applicationContext.xml(父容器):

<context:component-scan base-package="xxx.xx.xx"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> 注:这里的include-filter,exclude-filter分别表示白名单过滤和黑名单过滤。 通过如上的配置,就能实现bean加载的细粒度化, 对于component包扫描器的详细介绍可以看以下博客

转载请注明原文地址: https://www.6miu.com/read-2150019.html

最新回复(0)