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 一樣,能裝載類文件,但是使用時有區(qū)別,具體區(qū)別如下:
- ServiceLoader裝載的是一系列有某種共同特征的實現(xiàn)類,而ClassLoader是個萬能加載器;
- ServiceLoader裝載時需要特殊的配置,使用時也與ClassLoader有所區(qū)別;
- ServiceLoader還實現(xiàn)了Iterator接口。
示例
下面是關(guān)于ServiceLoader的簡單的例子,僅供參考
- 基礎(chǔ)服務(wù):IService
package com.service;
public interface IService {
String sayHello();
String getScheme();
}
- 具體服務(wù)實現(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ù)實現(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
- 測試類
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 把定義的兩個實現(xiàn)類找出來,返回一個 ServiceLoader 的實現(xiàn),而 ServiceLoader 實現(xiàn)了 Iterable 接口,所以可以通過 ServiceLoader 來遍歷所有在配置文件中定義的類的實例。
應(yīng)用
參考 Mybaits源碼解讀 驅(qū)動加載部分