2020-03-25-Java ServiceLoader(转).md


layout: post
title: Java安全模型(AccessController)(转)
categories: [Java]
description: Java安全模型(AccessController)
keywords: Java, AccessController


转载自 ServiceLoader详解

定义

A simple service-provider loading facility.

A service is a well-known set of interfaces and (usually abstract) classes. A service provider is a specific implementation of a service. The classes in a provider typically implement the interfaces and subclass the classes defined in the service itself. Service providers can be installed in an implementation of the Java platform in the form of extensions, that is, jar files placed into any of the usual extension directories. Providers can also be made available by adding them to the application's class path or by some other platform-specific means.

通俗讲,ServiceLoader 也像 ClassLoader 一样,能装载类文件,但是使用时有区别,具体区别如下:

  1. ServiceLoader装载的是一系列有某种共同特征的实现类,而ClassLoader是个万能加载器;
  2. ServiceLoader装载时需要特殊的配置,使用时也与ClassLoader有所区别;
  3. ServiceLoader还实现了Iterator接口。

示例

下面是关于ServiceLoader的简单的例子,仅供参考

  1. 基础服务:IService
package com.service;

public interface IService {
    String sayHello();
    String getScheme();
}
  1. 具体服务实现1:HDFSService
package com.impl;

import com.service.IService;

public class HDFSService implements IService {
    @Override
    public String sayHello() {
    return "Hello HDFSService";
  }
  
  @Override
  public String getScheme() {
    return "hdfs";
  }
}
  1. 具体服务实现2:LocalService
package com.impl;

import com.service.IService;

public class LocalService implements IService {

    @Override  
    public String sayHello() {
    return "Hello LocalService";
  }  
  @Override 
  public String getScheme() {
    return "local";  
  }
}
  1. 配置:META-INF/services/com.service.IService
com.impl.HDFSServicecom.impl.LocalService
  1. 测试类
package com.test;

import java.util.ServiceLoader;
import com.service.IService;

public class Test {

    public static void main(String[] args) {
    ServiceLoader serviceLoader = ServiceLoader.load(IService.class);
    for(IService service : serviceLoader) {
        System.out.println(service.getScheme()+"="+service.sayHello());
    }  
  }
}
  1. 结果:
hdfs=Hello HDFSService
local=Hello LocalService

可以看到 ServiceLoader 可以根据 IService 把定义的两个实现类找出来,返回一个 ServiceLoader 的实现,而 ServiceLoader 实现了 Iterable 接口,所以可以通过 ServiceLoader 来遍历所有在配置文件中定义的类的实例。

应用

参考 Mybaits源码解读 驱动加载部分

你可能感兴趣的:(2020-03-25-Java ServiceLoader(转).md)