【发布时间】:2014-04-07 15:52:29
【问题描述】:
当我需要一些 bean 时,我有一个有时不存在的范围。这本身不是问题。对于这些情况,我可以使用默认值。我的问题是自动装配。场景大致是这样的:
- 我有一个作用域 bean
ICurrentLocale。它的作用域是User,作用域取决于用户当前是否登录。 - Autowire bean
foo包含一个字段@Autowired ICurrentLocale currentLocale; - 在
foo上调用一些方法。 - 用户登录。现在,我有一个范围
User - 在
foo上调用一些方法。
我的问题是,在第 5 点中,自动装配的 ICurrentLocale bean 仍然相同,尽管在用户范围内创建了一个新 bean。
是否有一种好的/简单/可理解的方法来构建一个 spring 配置,当在同一个线程中输入新范围时自动重新连接 bean?
或者我可以让 Spring “刷新”代理?
编辑这是我当前的范围实现:
@Override
public Object get( String name, final ObjectFactory<?> objectFactory ) {
CurrentUserSession currentSession = userSessionFactory.getCurrentSession();
if( currentSession == null ) {
if( isLocaleProvider( name ) ) {
return createLocaleProvider();
}
throw new BeanCreationException( "Could not create bean " + name + " the bean scope " + NAME + " can be used only after the user has signed in" );
}
Object bean = currentSession.getBean(name, objectFactory);
return bean;
}
如您所见,只要没有用户登录,我就会创建一个虚拟 bean。如果我有会话,我会查看会话中的缓存。如果 bean 尚不存在,我使用 objectFactory 创建一个新的。
【问题讨论】:
-
向我们展示您的
UserScope实现。 -
@SotiriosDelimanolis:给你。
标签: java spring configuration scope