javascript
Spring范围代理
在這里,將原型作用域bean注入到Singleton作用域bean中。
現(xiàn)在,考慮使用以下bean進(jìn)行此測(cè)試:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class ScopedProxyTest {@Autowired private SingletonScopedBean singletonScopedBean;@Testpublic void testScopedProxy() {assertThat(singletonScopedBean.getState(), not(equalTo(singletonScopedBean.getState())));}@Configuration@ComponentScan("org.bk.samples.scopedproxy")public static class SpringContext{}}需要注意的是,這里僅創(chuàng)建了1個(gè)PrototypeScopedBean實(shí)例,并且將1個(gè)實(shí)例注入到SingletonScopedBean中,因此上述測(cè)試實(shí)際上期望每次調(diào)用getState()方法都會(huì)產(chǎn)生一個(gè)PrototypeScopedBean新實(shí)例失敗。 。
如果對(duì)PrototypeScopedBean的每個(gè)請(qǐng)求都需要一個(gè)新實(shí)例(并且通常,如果作用域較長的bean的作用域較短,則需要遵守較短的作用域),那么有幾種解決方案:
1.查找方法注入–可以在這里閱讀
2.更好的解決方案是使用范圍代理 -
可以使用@Configuration以這種方式指定作用域代理:
@Component @Scope(value="prototype", proxyMode=ScopedProxyMode.TARGET_CLASS) class PrototypeScopedBean{private final String state;public PrototypeScopedBean(){this.state = UUID.randomUUID().toString();}public String getState() {return state;}}進(jìn)行此更改后,注入到SingletonScopedBean中的bean并不是PrototypeScopedBean本身,而是該bean的代理(使用CGLIB或Dynamic代理創(chuàng)建),并且該代理了解范圍并根據(jù)范圍的要求返回實(shí)例,測(cè)試應(yīng)現(xiàn)在可以正常工作了。
參考: all和其他博客中的JCG合作伙伴 Biju Kunjummen提供的Spring Scoped Proxy 。
翻譯自: https://www.javacodegeeks.com/2012/08/spring-scoped-proxy.html
總結(jié)
以上是生活随笔為你收集整理的Spring范围代理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 汉族的民族服饰特点是什么(汉族服饰特色介
- 下一篇: 苹果6splus怎么设置来电铃声(iph