-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Labels
Description
方式一 Spring boot的applicationContext.getBeansOfType
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ServiceLocator implements ApplicationContextAware{
/**
* 用于保存接口实现类名及对应的类
*/
private Map<String, IService> map;
/**
* 获取应用上下文并获取相应的接口实现类
* @param applicationContext
* @throws BeansException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
//根据接口类型返回相应的所有bean
Map<String, IService> map = applicationContext.getBeansOfType(IService.class);
}
public Map<String, IService> getMap() {
return map;
}
}方式二 ServiceLoader类
通过其的load方法加载出所有的实现类
ServiceLoader<MyInterface> loader = ServiceLoader.load(MyInterface.class);总结
以上两种方式,实现的功能都是一样的,实现方式不同,底层用的技术一样的,都是反射。至于选择哪一种,我建议如果项目中的接口实现类都被Spring托管了,那当然是直接用Spring了。如果没有用到Spring的话,那就用ServiceLoader,这个肯定是没有问题的。