如何在同一个bean中自动连接bean [英] How to autowire bean in same bean

查看:124
本文介绍了如何在同一个bean中自动连接bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将bean A的实例自动连接到A的同一个实例。如何通过注释(无XML)实现此目的。

I would like to autowire instance of bean A to the same instance of A. How can I achieve this with annotation (without XML).

示例: p>

Example:

@Service
public class A {

    @Autowire
    A a;

}

我也尝试过

@Service
public class A {

    A a;

    @Autowired
    public void setA(final A a) {
        this.a = a;
    }

}

但它不工作: - /

but it is not working too :-/

使用XML进行配置,如

Configuration using XML like

<bean id="a" class="A">
    <property name="a" ref="a" />
</bean>

工作正常。也可以使用

@Service
public class A implements InitializingBean {

    A a;

    @Autowired
    ApplicationContext ctx;

    @Override
    public void afterPropertiesSet() throws Exception {
        a = ctx.getBean(A.class);
    }

}

但这很麻烦。奇怪的是,Spring可以在使用XML配置时处理这个问题,但是在使用基于注释的时候不能处理。

but this is cumbersome. The strange thing is, that Spring can handle this when using XML configuration, but not when using annotation-based one.

推荐答案

code> @Autowired 在查找autowire候选人时,跳过注释的bean,请改用 @Resource

@Autowired skip the annotated bean when looking for autowire candidates, use @Resource instead.

这篇关于如何在同一个bean中自动连接bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆