当singleton Bean依赖propotype Bean,可以使用在配置Bean添加look-method来解决
在Spring里面,當(dāng)一個(gè)singleton bean依賴一個(gè)prototype bean,因?yàn)閟ingleton bean是單例的,因此prototype bean在singleton bean里面也會(huì)變成單例.
這個(gè)怎么解決呢???可以使用Spring提供的lookup-method來(lái)注入。
舉例說(shuō)明:先列出相關(guān)類:代碼中的說(shuō)明足夠說(shuō)明問(wèn)題。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* 當(dāng)singleton Bean依賴propotype Bean,可以使用在配置Bean添加look-method來(lái)解決* @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為原型的獲取實(shí)例--><bean id ="lookupMethod" class="com.cn.springTest.LookupMethod"><!-- <property name="user" ref="user"/> --> <!-- 這種寫法會(huì)將user當(dāng)著單例來(lái)獲取--><lookup-method name="getUser" bean="user"/><!--lookup-method方式會(huì)將user當(dāng)著原型來(lái)獲取--></bean>?
測(cè)試類: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());}}?
注:在測(cè)試的時(shí)候除了spring相關(guān)包,發(fā)現(xiàn)缺少cglib-jar包。
<dependency>
??? <groupId>cglib</groupId>
??? <artifactId>cglib</artifactId>
??? <version>3.1</version>
</dependency>
?
轉(zhuǎn)載于:https://www.cnblogs.com/xubiao/p/5852445.html
總結(jié)
以上是生活随笔為你收集整理的当singleton Bean依赖propotype Bean,可以使用在配置Bean添加look-method来解决的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 无线网卡连接上没网络连接怎么办 无线网卡
- 下一篇: u盘文件打开遇到错误怎么办啊 解决u盘文