SpringFactoriesLoader提供了一种工厂方式供spring容器来加载特定的服务。像java的SPI一样,约定固定的配置文件和格式,使用SpringFactoriesLoader进行按需加载。只不过SpringFactoriesLoader读取的配置文件位置 “META-INF/spring.factories”。这个文件可以存在多个jar包中,只要在classpath下就可以读取到。spring.factories是一个properties文件,以key=value形式来配置服务接口与实现。多个value可以用英文逗号隔开,多个jar包中不同的spring.factories可以指定相同的key,然后会自动将所有的实现value合并成一个list。
来看下具体的使用,编写测试接口和实现类
定义一个接口
public interface MySpringFactoryService {void sayHello();
}
写两个实现类
public class MySpringFactoryServiceImpl1 implements MySpringFactoryService {@Overridepublic void sayHello() {System.out.println("service1");}
}public class MySpringFactoryServiceImpl2 implements MySpringFactoryService {@Overridepublic void sayHello() {System.out.println("service2");}
}
然后在resources目录下创建META-INF/spring.factories文件,配置如下
com.cpx.service.MySpringFactoryService=com.cpx.service.MySpringFactoryServiceImpl1,com.cpx.service.MySpringFactoryServiceImpl2
读取服务
1、读取配置接口名称
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(MySpringFactoryService.class, null);
configurations.forEach((s -> {System.out.println(s);
}));
可以打印输出配置的两个实现类:
com.cpx.service.MySpringFactoryServiceImpl1
com.cpx.service.MySpringFactoryServiceImpl2
2、获取服务实例
List<MySpringFactoryService> mySpringFactoryServices = SpringFactoriesLoader.loadFactories(MySpringFactoryService.class, null);
mySpringFactoryServices.forEach(MySpringFactoryService::sayHello);
调用两个接口实现类方法成功,输出:
service1
service2
配置value的时候,value对应的类必须是key的子类或实现类。因为在实例化的时候会有isAssignableFrom判断。并且构造函数也有要求。
SpringFactoriesLoader在springboot框架中有大量使用,可以根据spring的规范实现其扩展接口,实现自己的功能。