layout: post
title: Java安全模型(AccessController)(轉(zhuǎn))
categories: [Java]
description: Java安全模型(AccessController)
keywords: Java, AccessController
轉(zhuǎn)載自 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 一樣,能裝載類文件,但是使用時(shí)有區(qū)別豌鸡,具體區(qū)別如下:
- ServiceLoader裝載的是一系列有某種共同特征的實(shí)現(xiàn)類慢宗,而ClassLoader是個(gè)萬能加載器锈至;
- ServiceLoader裝載時(shí)需要特殊的配置众雷,使用時(shí)也與ClassLoader有所區(qū)別稚晚;
- ServiceLoader還實(shí)現(xiàn)了Iterator接口姻采。
示例
下面是關(guān)于ServiceLoader的簡(jiǎn)單的例子雅采,僅供參考
- 基礎(chǔ)服務(wù):IService
package com.service;
public interface IService {
String sayHello();
String getScheme();
}
- 具體服務(wù)實(shí)現(xiàn)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";
}
}
- 具體服務(wù)實(shí)現(xiàn)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";
}
}
- 配置:META-INF/services/com.service.IService
com.impl.HDFSServicecom.impl.LocalService
- 測(cè)試類
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());
}
}
}
- 結(jié)果:
hdfs=Hello HDFSService
local=Hello LocalService
可以看到 ServiceLoader 可以根據(jù) IService 把定義的兩個(gè)實(shí)現(xiàn)類找出來,返回一個(gè) ServiceLoader 的實(shí)現(xiàn)慨亲,而 ServiceLoader 實(shí)現(xiàn)了 Iterable 接口婚瓜,所以可以通過 ServiceLoader 來遍歷所有在配置文件中定義的類的實(shí)例。
應(yīng)用
參考 Mybaits源碼解讀 驅(qū)動(dòng)加載部分