简体   繁体   中英

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. Inside this class is a TheData object.

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

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

    </bean>

and a setter inside TheClass like so:

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?). 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.

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.

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

你可以使用@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). You can leverage the @Configurable annotation in the manner that is described in this blog post

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. That is:

public class TheClass {
  @Autowired
  private TheData theData;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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