Spring lookup-method
来源:互联网 发布:苹果付费画图软件 编辑:程序博客网 时间:2024/06/01 13:45
先看一下这段代码有什么问题?
public class WhlCarrier {}
public class HjlCarrier { private WhlCarrier whlCarrier; public void setWhlCarrier(WhlCarrier whlCarrier){ this.whlCarrier=whlCarrier; } public WhlCarrier getWhlCarrier() { return whlCarrier; }}
<bean id="whl" class="com.vo.collection.WhlCarrier" scope="prototype"> </bean> <bean id="hjl" class="com.vo.collection.HjlCarrier"> <property name="whlCarrier" ref="whl"/> </bean>
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration({"classpath:beans.xml"})public class TestLookup { @Autowired HjlCarrier hjlCarrier; @Test public void test() { System.out.println(hjlCarrier.getWhlCarrier() == hjlCarrier.getWhlCarrier()); }}运行的结果为true ,从配置文件可以看出我们把WhlCarrier配置成原型模式,HjlCarrier配置成单例模式。有时我们会很粗心的认为结果会返回false,因为我们把WhlCarrier设置成了原型模式,每次返回都不是同一个实例了,但别忘记了我们把HjlCarrier设置成了单例,也就是说HjlCarrier只出被实例化一次,里面的依赖也只会被设置一次,无法实时更新。要解决这个问题一般有两种方法,一是直接得到spring容器并主动向容器请求依赖的bean,这样做到实时更新,不好的地方就是有侵入式设计,不推荐。二是使用
lookup-method。下面我们来重写一下上面的代码:
public class WhlCarrier {}
public abstract class HjlCarrier { private WhlCarrier whlCarrier; public abstract WhlCarrier getEntity(); public WhlCarrier getWhlCarrier() { return getEntity(); }}
<bean id="whl" class="com.vo.collection.WhlCarrier" scope="prototype"> </bean> <bean id="hjl" class="com.vo.collection.HjlCarrier"> <lookup-method name="getEntity" bean="whl"/> </bean>
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration({"classpath:beans.xml"})public class TestLookup { @Autowired HjlCarrier hjlCarrier; @Test public void test() { System.out.println(hjlCarrier.getWhlCarrier() == hjlCarrier.getWhlCarrier()); } }
执行单元测试结果为false ,lookup 方法注入,Spring通过使用CGLIB库修改客户端的二进制码,从而实现我们在单例依赖原型时得到实时的实例。一般单例依赖单例,原型依赖单例不会有这样的问题。好了就这样吧,收工,跑步去。
0 0
- spring-"lookup-method"
- Spring lookup-method
- Spring - lookup-method使用示例
- spring Method injection Lookup method injection
- spring lookup-method和replace-method本质
- spring-study--lookup-method--replaced-method用法
- Spring的方法注入lookup-method
- spring bean中子元素lookup-method和replaced-method
- 《Spring 技术手册》3.2.6 Lookup Method Injection 笔记
- Spring的方法注入lookup-method(转)
- 码农小汪-spring框架学习之3-spring Method injection(方法注入 ) Lookup method injection
- Spring的XML配置文件中的bean的子元素lookup-method的作用是什么
- Spring(07)——单例注入多例之lookup-method
- Spring Bean的作用域以及lookup-method标签的使用
- spring Lookup方法注入
- spring 的 lookup方法注入
- lookup
- c++ 学习 笔记 之 template name lookup method:ADL
- 第三周项目4:穷举法解决组合问题(3)年龄几何
- PAT--1115. Counting Nodes in a BST
- 《剑指offer》——二叉树的下一个结点
- iOS多线程开发
- BZOJ-1877 晨跑 最小费用最大流+拆点
- Spring lookup-method
- 两步搞定 Tomcat 下启用 https:// 访问
- 一维数组实现杨辉三角
- 函数(-)
- make命令
- 博客专栏目录页
- Android照片墙完整版,完美结合LruCache和DiskLruCache
- Andrew NG UFLDL讲义学习代码之Logistic Regression
- 9个offer,12家公司,35场面试,从微软到谷歌,应届计算机毕业生的2012求职之路