我可以有一个定义类型T的bean,以及一个返回类型T的工厂bean吗?

时间:2012-12-05 19:35:50

标签: java spring ioc-container

我有一个请求范围的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;
    }
}

0 个答案:

没有答案