我有一个返回当前用户的请求范围 bean:
<bean id="currentUserResolver" class="com.shutup.CurrentUserResolver" />
<bean scope="request" factory-bean="currentUserResolver" factory-method="getCurrentUser">
<aop:scoped-proxy/>
</bean>
这样我就可以自动装配一个用户对象并获取当前用户。我还想做的是修改我的 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 紧密联系起来。
当前用户解析器:
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;
}
}