首先看一下Spring文档上的两个例子对比:
另外一个例子:
前一个例子没有使用
项目中代码如下:
public class PvgScope extends RequestScope {
public Object get(String name, ObjectFactory objectFactory) {
Object scopedObject = null;
try {
if (RequestContextHolder.getRequestAttributes() == null) {
scopedObject = PrivilegeInfo.getDummyPrivilegeInfo();
}
scopedObject = super.get(name, objectFactory);
} catch (IllegalStateException e) {
scopedObject = PrivilegeInfo.getDummyPrivilegeInfo();
}
return scopedObject;
}
}
这段代码是什么意思啊?求解释。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果题主只考虑容器对bean的实例化,scoped-proxy确实没什么意义。
scoped-proxy的意义在关联bean之间的依赖时才能体现。
这里userManager的作用域是singleton,也就是容器中仅初始化一次。
假设userPreferences因为userManager的作用域的原因只能被注入一次,换句话说,userManager以后使用的userPreferences永远都是同一个。
这样比较反直觉,我明明把userPreferences声明为session作用域,结果用到的时候跟这个作用域没有任何关系。
那么proxy,它代理的工作就是——暴露这个bean时令其符合其作用域的特性。
第二个例子中,userManager注入的是userPreferences的代理对象,当调用这个代理对象的方法时,会自动从httpsession中获取对应的userPreferences对象并调用其方法,从而实现在长生命周期对象里注入短生命周期的对象