参考博文: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())));
}
}