简体   繁体   English

如何在不是配置bean的类中自动装配bean?

[英]How to autowire a bean inside a class that is not a configured bean?

Forgive me if I don't get the terminology correct. 如果我的术语不正确,请原谅我。

My situation is thus: 我的情况是这样的:

I have a class, let's call it TheClass. 我有一个班级,我们称之为TheClass。 Inside this class is a TheData object. 这个类里面是一个TheData对象。

I have XML to set up the TheData bean, like so: 我有XML来设置TheData bean,如下所示:

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

    </bean>

and a setter inside TheClass like so: 和TheClass中的setter一样:

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

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?). 我的问题是,如果我不在XML中创建TheClass bean(因此不能让它自动装配),它将不知道自动装配theData字段(对吗?)。 And due to certain restrictions, I can't configure TheClass in the XML (and thus later have it autowired). 由于某些限制,我无法在XML中配置TheClass(因此后来将其自动装配)。 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. 我有点像新手,如果我错过了什么,请随意指出。

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上下文,则将其TheClass转换为AutowireCapableBeanFactory ,并将您的TheClass实例TheClassautowireBean(Object)方法。 Spring will then try to apply its autowiring rules to that object. 然后,Spring将尝试将其自动装配规则应用于该对象。

You'd need to add @Autowired to the setTheData method, though. 但是,您需要将@Autowired添加到setTheData方法中。

你可以使用@Resource或@Component。

I just now saw this question and thought I might add one more method of doing what you want (although the AutowireCapableBeanFactory would be my choice). 我刚刚看到这个问题,并认为我可能会添加另一种方法来做你想做的事情(虽然AutowireCapableBeanFactory将是我的选择)。 You can leverage the @Configurable annotation in the manner that is described in this blog post 您可以按照博客文章中描述的方式利用@Configurable批注

You should be able to just use the @Autowired annotation on your instance variable that your setter is setting, without having to declare a TheClass bean in your XML. 您应该能够在您的setter设置的实例变量上使用@Autowired注释,而无需在XML中声明TheClass bean。 That is: 那是:

public class TheClass {
  @Autowired
  private TheData theData;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM