Modus Operandi
Modus Operandi

Reputation: 641

Manually resolve a dependency in Spring [Boot]

This seems like it should be trivial, but both Google and StackOverflow seem to be just as uncooperative as Spring docs (or I just don't know where to look).

My Spring Boot application needs to manually instantiate certain classes. Some of the classes have dependencies, so I can't use .newInstance(); instead, I figure I need to ask Spring to give me the instance from its DI container. Something like

Class<? extends Interface> className = service.getClassName();
Interface x = SpringDI.getInstance(className);

But I can't seem to find any way of doing this. What should I do?

EDIT

Class names are resolved dynamically, I have updated my sample pseuido-code to reflect that.

Upvotes: 3

Views: 2837

Answers (1)

Andrei Balici
Andrei Balici

Reputation: 759

How about autowiring the ApplicationContext in the component in which you want to instantiate those classes? As ApplicationContext implements the BeanFactory interface, you can call the getBean() method.

Something like:

@Autowired
private ApplicationContext applicationContext;

[...]

applicationContext.getAutowireCapableBeanFactory().getBean(clazz_name);

I am not sure why you would want to do this, tho, as it defies the purpose of using Spring. (you can just not use Spring but use Java's reflection API)

Please refer to this part of the JavaDocs: http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/BeanFactory.html

Upvotes: 7

Related Questions