我可以使用Spring注入相同的类吗?

时间:2011-02-24 16:30:46

标签: java spring

我有一个类说UserService,它实现了Service并使用Service StereoType进行了注释,我正在使用Spring AOP并想为此做临时解决方法(I know this can be done in better way

@Service
public class UserService implements Service{
   @Autowired
   private Service self;
}

我试过这个但是得到了BeanNotFoundException,我错过了什么吗?

我知道我必须使用带有@Configurable的AspectJ,但只是寻找一些临时的解决方法

4 个答案:

答案 0 :(得分:5)

为什么你到底需要这样做?在您需要引用当前实例的任何方法中,即self,您只需使用this关键字。

我们错过了什么吗?如果您正在尝试做其他事情,请尝试澄清您的问题,我们会采取措施。

如果您想知道,这不起作用,因为在完全构造之前不能注入bean - >这意味着Spring必须注入bean的所有属性。实际上,你所做的是创建一个循环依赖,因为Spring试图实例化bean,当它发生时,它发现它需要Autowire另一个bean。当它试图找到那个bean时它不能,因为bean还没有被添加到初始化的bean列表中(因为它当前正在被初始化)。那有意义吗?这就是你得到BeanNotFoundException的原因,因为bean无法初始化。

答案 1 :(得分:1)

您可以将课程编辑为

@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON, proxyMode = ScopedProxyMode.INTERFACES)
public class UserService implements Service
{
    @Autowired
    private Service self;
}

这应该有效

答案 2 :(得分:0)

我知道这并没有完全回答这个问题,但我建议重新编写代码,这样你就不需要依赖应用于自我调用的方面了。例如,如果您有一些事务方法,只需确保在调用方法中正确设置事务内容。

如果真的需要,您可以创建类ApplicationContextAware并从上下文中获取bean-with-aspects

答案 3 :(得分:0)

这很好用 -

@Service(value = "someService")
public class UserService implements Service{
   @Resource(name = "someService")
   private Service self;
}