如何在未配置的bean的类中自动装配bean? [英] How to autowire a bean inside a class that is not a configured bean?

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

问题描述

如果我对术语不正确,请原谅我.

Forgive me if I don't get the terminology correct.

因此,我的情况是:

我有一个课,我们称它为TheClass.在此类的内部是TheData对象.

I have a class, let's call it TheClass. Inside this class is a TheData object.

我有XML来设置TheData bean,就像这样:

I have XML to set up the TheData bean, like so:

<bean id="theData" class="com.abc.TheData">
        <property name="field" value="value1" />

    </bean>

和TheClass中的setter一样:

and a setter inside TheClass like so:

public void setTheData(TheData theData)
{
     this.theData = theData;
}

我的问题是,如果我也没有在XML中创建TheClass bean(因此不能让它自动装配),它将不会自动装配theData字段(对吗?).并且由于某些限制,我无法在XML中配置TheClass(因此后来将其自动装配了).所以,我的问题是,我该如何进行这项工作?我是个新手,所以如果我缺少什么,请随时指出.

My problem is that if I don't also create the TheClass bean in the XML (and thus can't let it get autowired), it won't know to autowire the theData field (right?). And due to certain restrictions, I can't configure TheClass in the XML (and thus later have it autowired). So, my question is, how can I make this work? I'm a bit of a novice so if I'm missing something, feel free to point it out.

推荐答案

如果可以掌握Spring上下文,请将其强制转换为AutowireCapableBeanFactory,然后将TheClass的实例传递给autowireBean(Object)方法.然后,Spring将尝试将其自动装配规则应用于该对象.

If you can get hold of the Spring context, cast it to AutowireCapableBeanFactory, and pass your instance of TheClass to the autowireBean(Object) method. Spring will then try to apply its autowiring rules to that object.

不过,您需要将@Autowired添加到setTheData方法中.

You'd need to add @Autowired to the setTheData method, though.

这篇关于如何在未配置的bean的类中自动装配bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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