How to make an autwire bean inside a class that is not configured by a bean?

Forgive me if I do not get the right terminology.

My situation is this:

I have a class, let me call it TheClass. Inside this class is the TheData object.

I have XML to configure TheData bean, for example:

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

and setter inside TheClass, for example:

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

My problem is that if I do not create TheClass bean in XML (and therefore cannot allow autoload), it will not know how to auto-polish theData field (right?). And due to certain restrictions, I can not configure TheClass in XML (and, therefore, later automatically install it). So my question is: how can I do this? I am a little newbie, so if I miss something, feel free to point it out.

+4
source share
4 answers

If you can get the Spring context, drop it to AutowireCapableBeanFactory and pass your instance of TheClass to the autowireBean(Object) method. Spring will try to apply its auto-rules to this object.

You need to add @Autowired to the setTheData method.

+4
source

You can use @Resource or @Component.

0
source

I just saw this question now and thought I could add another way to do what you want (although AutowireCapableBeanFactory would be my choice). You can use the @Configurable annotation in the way described in this blog post

0
source

You should be able to simply use the @Autowired annotation in the instance variable that your setter sets without declaring the TheClass bean declaration in your XML. I.e:

 public class TheClass { @Autowired private TheData theData; } 
-1
source

Source: https://habr.com/ru/post/1334981/


All Articles