简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM