spring总的上下文容器有父子之分,父容器和子容器。 ** 父容器对子容器可见,子容器对父容器不可见 ** 。
对于传统的spring mvc来说,spring mvc容器为子容器,也就是说ServletDispatcher对应的容器为子容器,而web.xml中通过ConextLoaderListener的contextConfigLocation属性配置的为父容器。
父子容器的使用场景
父子容器的主要用途是上下文隔离。考虑以下一种场景。
- project-service.jar为服务层模块。包含一些数据库service方法。其对应的spring配置文件为project-service.xml。
- project-api为api服务器代码。它依赖于project-service.jar。其对应的配置文件为project-api.xml。
project-api需要对project-service里的某些方法进行decorate,进行装饰,比如给CustomerService进行装饰。装饰后的类为CachedCustomerService。于是,现在project-api里面包含两个CustomerService,一个是来自project-service的CustomerService,另一个是CachedCustomerService。这个时候,如果project-api工程所有的配置文件都通过一个上下文进行加载,势必出现问题(通常的做法是用import标签全部给import进来)。因为,project里的PayService里通过@Resource标准注入了CustomerService,类似如下
1
2
3
4
5
|
@Serivce
public class PayService{
@Resource
private CustomerService cusService;
}
|
解决方式
这时,由于上下文在注入customerService属性的时候,遇到了两个CustomService。它无法判读注入哪个Service。
当然了,有人会说,改一下PayService的Resource属性,指定下具体注入哪个。但是,project-service.jar是第三方库的话,改动代码变得不可行,除非拿到源码。
这个时候,就可以通过父子容器的方式解决这个问题。
将project-service放在父容器中,project-api所有的bean用子容器加载。
假设project-api的上下文配置文件为project-api.xml,实现方法如下。
1、定义project-total.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
< bean id = "serviceContext" class = "org.springframework.context.support.ClassPathXmlApplicationContext" >
< constructor-arg >
< value >
classpath:project-service.xml
</ value >
</ constructor-arg >
</ bean >
< bean id = "apiContext" class = "org.springframework.context.support.ClassPathXmlApplicationContext" >
< constructor-arg >
< value >
classpath:project-api.xml
</ value >
</ constructor-arg >
< constructor-arg >
< ref bean = "serviceContext" />
</ constructor-arg >
</ bean >
|
2、在web.xml的上下文配置中如下。
1
2
3
4
5
6
7
8
9
10
11
12
|
< context-param >
< param-name >contextConfigLocation</ param-name >
< param-value > classpath*:project-total.xml</ param-value >
</ context-param >
< listener >
< listener-class >org.springframework.web.util.Log4jConfigListener</ listener-class >
</ listener >
< listener >
< listener-class >org.springframework.web.context.ContextLoaderListener</ listener-class >
</ listener >
|
serviceContext为父容器,apiContext为子容器,从而实现serviceContext看不到apiContext,而apiContext可以看见serviceContext的效果。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。
原文链接:https://www.jianshu.com/p/d9db47b5fc54
相关文章
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
-
2025-05-27 97
-
2025-05-27 24
-
2025-06-04 100
-
2025-05-29 28
-
Ubuntu 20.04服务器安装配置phpMyAdmin教程
2025-05-25 64