标签:
在Spring里面,当一个singleton bean依赖一个prototype bean,因为singleton bean是单例的,因此prototype bean在singleton bean里面也会变成单例.
这个怎么解决呢???可以使用Spring提供的lookup-method来注入。
举例说明:先列出相关类:代码中的说明足够说明问题。user类:prototype bean
package com.cn.pojo; import java.io.Serializable; public class User implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private int userId; private String userName; private String userPwd; private String userInfo; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPwd() { return userPwd; } public void setUserPwd(String userPwd) { this.userPwd = userPwd; } public String getUserInfo() { return userInfo; } public void setUserInfo(String userInfo) { this.userInfo = userInfo; } }
LookupMethod类:singleton bean
package com.cn.springTest; import com.cn.pojo.User; /** * LookupMethod为singleton,user为propotype * 当singleton Bean依赖propotype Bean,可以使用在配置Bean添加look-method来解决 * @author Administrator * */ public class LookupMethod { private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
核心配置文件:
<!-- user userbean --> <bean id ="user" class="com.cn.pojo.User" scope="prototype"> <property name="userId" value="1" /> <property name="userName" value="userName" /> <property name="userPwd" value="userPwd" /> <property name="userInfo" value="userInfo" /> </bean> <!-- lookupMethod LookupMethod为单例,user为原型的获取实例--> <bean id ="lookupMethod" class="com.cn.springTest.LookupMethod"> <!-- <property name="user" ref="user"/> --> <!-- 这种写法会将user当着单例来获取--> <lookup-method name="getUser" bean="user"/><!--lookup-method方式会将user当着原型来获取--> </bean>
测试类:SpringLookupMethod
import com.cn.util.SpringContextUtil; public class SpringLookupMethod { public static void main(String[] args) { ApplicationContext actx = new ClassPathXmlApplicationContext("ApplicationContext.xml"); actx.getBean("springContextUtil"); LookupMethod lookupMethod = (LookupMethod) SpringContextUtil.getBean("lookupMethod"); System.out.println(lookupMethod); LookupMethod lookupMethod1 = (LookupMethod) SpringContextUtil.getBean("lookupMethod"); System.out.println(lookupMethod1); System.out.println(lookupMethod.getUser()); System.out.println(lookupMethod1.getUser()); System.out.println(lookupMethod.getUser()); System.out.println(lookupMethod1.getUser()); } }
这样的测试足够说明问题。
当singleton Bean依赖propotype Bean,可以使用在配置Bean添加look-method来解决
标签:
原文地址:http://www.cnblogs.com/xubiao/p/5852445.html