之前有写过一篇文章–>[java之spi机制简介]不了解spi的朋友,可以先查阅这篇文章了解下,再阅读下文
假设大家已经对SPI有一定的了解,有使用过JDK提供的SPI的朋友,应该会发现JDK的SPI是无法实现按需加载。那如何解决这个短板问题?
这边提供2种思路,一种是自己实现一套SPI,另外一种在实现组件很常用的手段,就是当前组件无法满足时,可以借助其他组件或者再加代理层。本文实现的思路,就是利用spring的IOC,spring的ioc本质上就是一个键值对map,将jdk spi生成的对象注入到spring ioc容器中,间接也拥有了key–>value的映射功能
1、spi加载实现
public Map<String,T> getSpiMap(Class<T> clz){ listServicesAndPutMapIfNecessary(clz,true); return spiMap; } private List<T> listServicesAndPutMapIfNecessary(Class<T> clz,boolean isNeedPutMap){ List<T> serviceList = new ArrayList(); ServiceLoader<T> services = ServiceLoader.load(clz); Iterator<T> iterator = services.iterator(); while(iterator.hasNext()){ T service = iterator.next(); serviceList.add(service); setSevices2Map(isNeedPutMap, service); } return serviceList; } @SneakyThrows private void setSevices2Map(boolean isNeedPutMap, T service) { if(isNeedPutMap){ String serviceName = StringUtils.uncapitalize(service.getClass().getSimpleName()); service = getProxyIfNecessary(service); spiMap.put(serviceName,service); } }
2、注入spring容器
public class SpiRegister implements ImportBeanDefinitionRegistrar,BeanFactoryAware { private DefaultListableBeanFactory beanFactory; @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { registerSingleton(importingClassMetadata); } private void registerSingleton(AnnotationMetadata importingClassMetadata) { Class<?> spiInterface = getSpiInterface(importingClassMetadata); if(spiInterface != null){ Map<String,?> spiMap = new SpiFactory().getSpiMap(spiInterface); if(MapUtil.isNotEmpty(spiMap)){ spiMap.forEach((beanName,bean) -> { registerSpiInterfaceSingleton(spiInterface, bean); beanFactory.registerSingleton(beanName,bean); }); } } } private void registerSpiInterfaceSingleton(Class<?> spiInterface, Object bean) { Spi spi = spiInterface.getAnnotation(Spi.class); String defalutSpiImplClassName = spi.defalutSpiImplClassName(); if(StringUtils.isBlank(defalutSpiImplClassName)){ defalutSpiImplClassName = spi.value(); } String beanName = bean.getClass().getName(); if(bean.toString().startsWith(SpiProxy.class.getName())){ SpiProxy spiProxy = (SpiProxy) Proxy.getInvocationHandler(bean); beanName = spiProxy.getTarget().getClass().getName(); } if(beanName.equals(defalutSpiImplClassName)){ String spiInterfaceBeanName = StringUtils.uncapitalize(spiInterface.getSimpleName()); beanFactory.registerSingleton(spiInterfaceBeanName,bean); } } private Class<?> getSpiInterface(AnnotationMetadata importingClassMetadata) { List<String> basePackages = getBasePackages(importingClassMetadata); for (String basePackage : basePackages) { Reflections reflections = new Reflections(basePackage); Set<Class<?>> spiClasses = reflections.getTypesAnnotatedWith(Spi.class); if(!CollectionUtils.isEmpty(spiClasses)){ for (Class<?> spiClass : spiClasses) { if(spiClass.isInterface()){ return spiClass; } } } } return null; } private List<String> getBasePackages(AnnotationMetadata importingClassMetadata) { Map<String, Object> enableSpi = importingClassMetadata.getAnnotationAttributes(EnableSpi.class.getName()); String[] spiBackagepackages = (String[]) enableSpi.get("basePackages"); List<String> basePackages = Arrays.asList(spiBackagepackages); if(CollectionUtils.isEmpty(basePackages)){ basePackages = new ArrayList<>(); basePackages.add(ClassUtils.getPackageName(importingClassMetadata.getClassName())); } return basePackages; } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = (DefaultListableBeanFactory)beanFactory; } }
1、定义spi服务接口
@Spi public interface HelloService { String sayHello(String username); }
注: @Spi用来指定哪些spi服务接口需要注入到spring 容器中,同时@Spi还有一个defalutSpiImplClassName属性,用来指定默认注入spi实现类
2、定义具体实现类
public class HelloServiceCnImpl implements HelloService { @Override @InterceptorMethod(interceptorClasses = {HelloServiceCnInterceptor.class, HelloServiceCnOtherInterceptor.class}) public String sayHello(String username) { return "你好:" + username; } }
public class HelloServiceEnImpl implements HelloService { @Override @InterceptorMethod(interceptorClasses = HelloServiceEnInterceptor.class) public String sayHello(String username) { return "hello:" + username; } }
注: @InterceptorMethod这个注解是用来做方法增强,和本文的关系不大,可以忽略
3、src/main/resources/下建立/META-INF/services 目录,新增一个以接口命名的文件
com.github.lybgeek.spi.HelloService
4、接口命名的文件填入如下内容
com.github.lybgeek.spi.en.HelloServiceEnImpl
com.github.lybgeek.spi.cn.HelloServiceCnImpl
5、编写业务controller
@RestController @RequestMapping("/test") public class SpiTestController { @SpiAutowired("helloServiceCnImpl") private HelloService helloService; @GetMapping(value="/{username}") public String sayHello(@PathVariable("username") String username){ return helloService.sayHello(username); } }
注: @SpiAutowired是一个自定义注解,该注解可以看成是@Autowired + @Qualifier
6、启动类上加@EnableSpi(basePackages = “com.github.lybgeek.spi”)
注: basePackages用来指定扫描spi的包
7、测试
此时页面渲染为
注: 这边没有用@SpiAutowired,是因为@SpiAutowired需要指定名称
本文基于spi按需加载是依赖spring,在某种程度上和spring耦合,有机会的话,再讲下如何实现自定义键值对SPI