在spring中,prototype scoped bean 如何注入单例bean中

        参考博文:http://www.javacodegeeks.com/2012/08/spring-scoped-proxy.html

        如何对一个生命周期为ConfigurableBeanFactory.SCOPE_PROTOTYPE即原型的bean注入到一个ConfigurableBeanFactory.SCOPE_SINGLETON即单例bean中,利用配置proxyMode = ScopedProxyMode.TARGET_CLASS,每次单例bean中 获取这个 注入的原型bean的时候,利用CGLIB创建一个代理类。

详细见代理示例:

/**
 * How a prototype scoped bean is injected into a Singleton scoped bean.
 * 
 * use:proxyMode = ScopedProxyMode.TARGET_CLASS
 * 
 * @author doctor
 *
 * @time 2015年4月15日
 */
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class PrototypeScopedBean {
	private final String state;

	public PrototypeScopedBean() {
		this.state = UUID.randomUUID().toString();
	}

	public String getState() {
		return state;
	}

}

/**
 * 
 * @author doctor
 *
 * @time 2015年4月15日
 */
@Component
public class SingletonScopedBean {

	@Resource
	private PrototypeScopedBean prototypeScopedBean;

	public String getState() {
		return prototypeScopedBean.getState();
	}
}


@Configuration
@ComponentScan(basePackages = "com.doctor.spring4.blog.code.spring_scoped_proxy")
public class SpringScopedProxyConfig {

}

测试用例:

package com.doctor.spring4.blog.code.spring_scoped_proxy;

import static org.junit.Assert.*;
import static org.hamcrest.core.IsEqual.*;
import static org.hamcrest.core.IsNot.*;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * How a prototype scoped bean is injected into a Singleton scoped bean.
 * 
 * @see http://www.javacodegeeks.com/2012/08/spring-scoped-proxy.html
 * @author doctor
 *
 * @time 2015年4月15日
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpringScopedProxyConfig.class })
public class SpringScopedProxyTest {
	@Resource
	private SingletonScopedBean singletonScopedBean;

	@Test
	public void test() {
		assertThat(singletonScopedBean.getState(), not(equalTo(singletonScopedBean.getState())));
	}

}


转载于:https://my.oschina.net/doctor2014/blog/402076

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值