Chris
Chris

Reputation: 89

Spring constructor injection

Is it possible to construct an object manually and let some other arguments be injected by Spring?

e.g.

 class A 
 @Autowired
 private SomeDao dao;
 A(String x, String y) {}

Upvotes: 0

Views: 267

Answers (3)

Your example is using field injection, not constructor injection.

The best way is generally to use JavaConfig. Your @Bean methods can take parameters (which Spring will autowire), which you can combine with your other options when you call new.

Upvotes: 1

Willian
Willian

Reputation: 522

You can use autowireBean from the AutowireCapableBeanFactory. Given your applicationContext, you call getAutowireCapableBeanFactory() and then autowire your instance:

applicationContext.getAutowireCapableBeanFactory().autowireBean( new A("x", "y" ) );

Upvotes: 0

mizin
mizin

Reputation: 1

Maybe org.springframework.web.context.support.SpringBeanAutowiringSupport class it's what you are looking for, try to invoke:

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

Upvotes: 0

Related Questions