• Now all data be ready for publish, We had made our blog alive now. Haha.

  • These days CCP GFW blocked all the IPs from US and when I switch my IP in google Cloud, the disk data cannot be restore again. I have to restart my blog totally, Now the website is still building…

How to inject dependencies into a self-instantiated object in Spring?- Stack Overflow

Java PingBook 1 months ago (10-23) 15 0


Let’s say we have a class:

public class MyClass {
@Autowired private AnotherBean anotherBean;

Then we created an object of this class (or some other framework have created the instance of this class).

MyClass obj = new MyClass();

Is it possible to still inject the dependencies? Something like:


(I think Google Guice has something like this)


You can do this using the autowireBean() method of AutowireCapableBeanFactory. You pass it an arbitrary object, and Spring will treat it like something it created itself, and will apply the various autowiring bits and pieces.

To get hold of the AutowireCapableBeanFactory, just autowire that:

private @Autowired AutowireCapableBeanFactory beanFactory;

public void doStuff() {
MyBean obj = new MyBean();
// obj will now have its dependencies autowired.

Copyright from PingBook Blog, If not specified, they are original. This site uses BY-NC-SAProtocol authenticated.
For reprinting, please indicate the link of the original text:How to inject dependencies into a self-instantiated object in Spring?- Stack Overflow
LIKE (0)
We create, We sharing! Tag every value data your sharing
Submit comments
Cancel comments
emoji picture bold strikethrough center italic check in

Hi,you need to provide your name and email adress!

  • Name (Required)
  • Email (Required)
  • Website