1. 创建SPI服务
1.1 在META-INF/services目录下创建相关服务文件
1.2 实现相关服务
1.3 在相关服务文件中指向实现服务
com.alibaba.edas.carshop.itemcenter.service.SingletonService
com.alibaba.edas.carshop.itemcenter.service.PrototypeService
2.相关注解
2.1 @Scope
指定获取实例是单例还是每次创建新实例
public @interface Scope {
Scope.Option value() default Scope.Option.SINGLETON;
public static enum Option {
SINGLETON,
PROTOTYPE;
private Option() {
}
}
}
2.2 @Name
为服务命名,可以通过命名的key来获取服务
2.3 @Tag
为服务打标签分组,跟@Name不同的地方是@Tag可以重复
2.4 @Order
为服务排序
2.5 注解测试
测试类
@Scope(Scope.Option.SINGLETON)
@Name("singletonService")
@Tag("singletonTagService")
@Order(2)
public class SingletonService implements NameService {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public SingletonService()
{
name="SINGLETON";
}
}
@Scope(Scope.Option.PROTOTYPE)
@Name("prototypeService")
@Tag("prototypeTagService")
@Order(1)
public class PrototypeService implements NameService {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public PrototypeService()
{
name="PROTOTYPE";
}
}
测试Demo
public class NameServiceTest {
@Test
public void test1()
{
//测试@Scope中的PROTOTYPE & @Order
{
List<NameService> service= HSFServiceContainer.getInstances(NameService.class, new String[0]);
System.out.print(service);
}
{
List<NameService> service= HSFServiceContainer.getInstances(NameService.class, new String[0]);
System.out.print(service);
}
//测试@Name
{
NameService service= HSFServiceContainer.getInstance(NameService.class, "singletonService");
System.out.print(service);
}
{
NameService service= HSFServiceContainer.getInstance(NameService.class, "prototypeService");
System.out.print(service);
}
//测试@Tag
{
List<NameService> service= HSFServiceContainer.getInstances(NameService.class, "prototypeTagService");
System.out.print(service);
}
}
}
3.服务初始化生命周期
在第一次实例创建的时候,接受FrameworkModelAware和ApplicationModelAware2个接口来获取FrameworkModel和ApplicationModel
private void awareInstance(Object instance) {
if (instance instanceof FrameworkModelAware) {
((FrameworkModelAware)instance).setFrameworkModel(ApplicationModel.frameworkModel);
}
if (instance instanceof ApplicationModelAware && this.application != null) {
((ApplicationModelAware)instance).setApplicationModel(this.application);
}
}