我有一个请求范围的bean,它返回当前用户:
<bean id="currentUserResolver" class="com.shutup.CurrentUserResolver" />
<bean scope="request" factory-bean="currentUserResolver" factory-method="getCurrentUser">
<aop:scoped-proxy/>
</bean>
这样我就可以自动装配User对象并获取当前用户。我还想做的是修改我的User类以使用init方法:
<bean id="user" class="com.shutup.model.User" init-method="postInitialize" />
如果我这样做,Spring会抱怨:
No unique bean of type [com.shutup.model.User] is defined: expected single matching bean but found 2: [user, currentUserResolver$created#0]
有没有办法以声明方式将postInitialize方法添加到用户?我相信我也可以选择User实现一个接口,但我宁愿不把我的代码紧密地绑在Spring上。
CurrentUserResolver:
public class CurrentUserResolver
{
static Log log = LogFactory.getLog(CurrentUserResolver.class.getName());
@Autowired
private UserFactory userFactory;
public User getCurrentUser()
{
log.info("attempting to get current user");
User currentUser = null;
if(SecurityContextHolder.getContext() != null &&
SecurityContextHolder.getContext().getAuthentication() instanceof UserAuthentication)
{
UserAuthentication authentication = (UserAuthentication)SecurityContextHolder.getContext().getAuthentication();
User serializedUser = (User)authentication.getPrincipal();
currentUser = this.userFactory.getUserFromTwitterId(serializedUser.getTwitterId());
}
return currentUser;
}
}