当singleton Bean依赖propotype Bean,可以使用在配置Bean添加look-method来解决
生活随笔
收集整理的這篇文章主要介紹了
当singleton Bean依赖propotype Bean,可以使用在配置Bean添加look-method来解决
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在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());}}?
注:在測試的時候除了spring相關包,發現缺少cglib-jar包。
<dependency>
??? <groupId>cglib</groupId>
??? <artifactId>cglib</artifactId>
??? <version>3.1</version>
</dependency>
?
轉載于:https://www.cnblogs.com/xubiao/p/5852445.html
總結
以上是生活随笔為你收集整理的当singleton Bean依赖propotype Bean,可以使用在配置Bean添加look-method来解决的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 无线网卡连接上没网络连接怎么办 无线网卡
- 下一篇: u盘文件打开遇到错误怎么办啊 解决u盘文