0

Suppose I have a POJO instance, which is annotated by @Autowired.

public class MyClass {
   @Autowired
   private Database database;
}

Can I invoke Spring processing for this instance programmatically, i.e. set database field from beans in the given context?

Dims
  • 47,675
  • 117
  • 331
  • 600

2 Answers2

1

It can be done manually for POJO's.

Autowire AutowireCapableBeanFactory in the caller class

@Autowired
AutowireCapableBeanFactory beanFactory;

In the function where this class needs to be used.

MyClass a = new MyClass().
beanFactory.autowireBean(a);

This will update all spring dependencies in the object a, including the database autowiring.

This is similar to How to inject dependencies into a self-instantiated object in Spring?

Community
  • 1
  • 1
Jaiprakash
  • 599
  • 2
  • 7
0

Yes you can given a Spring ApplicationContext you should be able to call autowireBean() or configureBean() with the suitable parameters.