Home > Java > javaTutorial > body text

How to Inject Dependencies into Self-Instantiated Objects in Spring?

Barbara Streisand
Release: 2024-10-29 23:46:29
Original
274 people have browsed it

How to Inject Dependencies into Self-Instantiated Objects in Spring?

Overcoming Injection Challenges for Self-Instantiated Objects in Spring

When working with Spring, it is common to manage dependencies through annotations and dependency injection. However, situations may arise where you have a self-instantiated object outside of the Spring context. In such cases, how can you still leverage Spring's injection capabilities?

The Dilemma: Manual Instantiation and Dependency Management

Consider the following scenario:

<code class="java">public class MyClass {
    @Autowired private AnotherBean anotherBean;
}

...

MyClass obj = new MyClass();</code>
Copy after login

You have instantiated MyClass manually but want to inject its dependencies like anotherBean. How do you go about it?

Solution: Utilizing the AutowireCapableBeanFactory

Spring provides the AutowireCapableBeanFactory interface, which enables us to inject dependencies into any arbitrary object, including self-instantiated ones. To access the BeanFactory:

<code class="java">private @Autowired AutowireCapableBeanFactory beanFactory;</code>
Copy after login

Injecting Dependencies into a Self-Instantiated Object

Using the beanFactory, you can inject dependencies into your object:

<code class="java">public void doStuff() {
   MyBean obj = new MyBean();
   beanFactory.autowireBean(obj);
   // obj will now have its dependencies autowired.
}</code>
Copy after login

After calling autowireBean, your instantiated object will have its dependencies injected and ready for use. This approach allows you to leverage Spring's dependency injection capabilities even for objects you create manually.

The above is the detailed content of How to Inject Dependencies into Self-Instantiated Objects in Spring?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!