Home  >  Article  >  Java  >  How can I inject dependencies into self-instantiated objects in Spring?

How can I inject dependencies into self-instantiated objects in Spring?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 09:39:02585browse

How can I inject dependencies into self-instantiated objects in Spring?

Dependency Injection for Self-Instantiated Objects in Spring

When creating instances of Spring-managed classes without using the Spring context (e.g., new MyClass()), it may be necessary to manually inject dependencies into those objects.

Solution Using AutowireCapableBeanFactory

Spring provides the AutowireCapableBeanFactory to address this scenario. By autowiring your beanFactory, you can inject dependencies into any arbitrary object:

<code class="java">@Autowired
private AutowireCapableBeanFactory beanFactory;

// Later in your code:
MyBean obj = new MyBean();
beanFactory.autowireBean(obj);</code>

After this, obj will have its dependencies automatically injected, as if it had been created by the Spring context.

The above is the detailed content of How can I inject dependencies into self-instantiated objects in Spring?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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