您现在的位置是:主页 > news > 网站开发实例pdf/网站关键词排名批量查询
网站开发实例pdf/网站关键词排名批量查询
admin2025/5/22 10:45:28【news】
简介网站开发实例pdf,网站关键词排名批量查询,淘宝客网站怎么做推广,做网站销售的近期在项目中需要实现能在配置文件中定义多个统一接口类型的类,可以在程序中获取到所有配置的类,刚开始打算配置到properties中,然后去程序读取,感觉这种方式不太灵活,于是,研究研究java中有没有这种支持&a…
近期在项目中需要实现能在配置文件中定义多个统一接口类型的类,可以在程序中获取到所有配置的类,刚开始打算配置到properties中,然后去程序读取,感觉这种方式不太灵活,于是,研究研究java中有没有这种支持,最终确认ServiceLoader可以实现这种功能,下面讲解如何使用ServiceLoader类。
首先定义一个接口程序的定义如下:
public interface IShareniuService {
public String sayHello();
public String getScheme();
}
public class ShareniuserverImp1 implements IShareniuService {
public String sayHello() {
return "shareniu1sayHello";
}
public String getScheme() {
return "shareniu1getScheme";
}
}
public String sayHello() {
return "shareniu2sayHello";
}
public String getScheme() {
return "shareniu2getScheme";
}
需要在META-INF/services下以IShareniuService这个类的全名来新建立一个文件,文件中的内容为两个实现类的全名,如下:
所有的实现和配置都已经完成,下面写一个测试类来看一下结果:
ServiceLoader serviceLoader = ServiceLoader
.load(IShareniuService.class);
for (IShareniuService service : serviceLoader) {
System.out.println(service.getScheme()+"="+service.sayHello());
}
具体的输出来如下:
shareniu2getScheme=shareniu2sayHello
shareniu1getScheme=shareniu1sayHello
可以看到ServiceLoader可以根据IShareniuService把定义的两个实现类找出来,返回一个ServiceLoader的实现,而ServiceLoader实现了Iterable接口,所以可以通过ServiceLoader来遍历所有在配置文件中定义的类的实例
hadoop中 FileSystem就是通过这个机制来根据不同文件的scheme来返回不同的FileSystem。
FileSystem中的相关实例如下:
private static void loadFileSystems() {
synchronized (FileSystem.class) {
if (!FILE_SYSTEMS_LOADED) {
ServiceLoader serviceLoader = ServiceLoader.load(FileSystem.class);
for (FileSystem fs : serviceLoader) {
SERVICE_FILE_SYSTEMS.put(fs.getScheme(), fs.getClass());
}
FILE_SYSTEMS_LOADED = true;
}
}
}
FileSystem对应的配置如下:
org.apache.hadoop.fs.LocalFileSystem
org.apache.hadoop.fs.viewfs.ViewFileSystem
org.apache.hadoop.fs.s3.S3FileSystem
org.apache.hadoop.fs.s3native.NativeS3FileSystem
org.apache.hadoop.fs.kfs.KosmosFileSystem
org.apache.hadoop.fs.ftp.FTPFileSystem
org.apache.hadoop.fs.HarFileSystem
通过之前的测试类输出对应的scheme和class如下:
file=class org.apache.hadoop.fs.LocalFileSystem
viewfs=class org.apache.hadoop.fs.viewfs.ViewFileSystem
s3=class org.apache.hadoop.fs.s3.S3FileSystem
s3n=class org.apache.hadoop.fs.s3native.NativeS3FileSystem
kfs=class org.apache.hadoop.fs.kfs.KosmosFileSystem
ftp=class org.apache.hadoop.fs.ftp.FTPFileSystem
har=class org.apache.hadoop.fs.HarFileSystem
hdfs=class org.apache.hadoop.hdfs.DistributedFileSystem
hftp=class org.apache.hadoop.hdfs.HftpFileSystem
hsftp=class org.apache.hadoop.hdfs.HsftpFileSystem
webhdfs=class org.apache.hadoop.hdfs.web.WebHdfsFileSystem
可以看到FileSystem会把所有的FileSystem的实现都以scheme和class来cache,之后就从这个cache中取相应的值。
因此,以后可以通过ServiceLoader来实现一些类似的功能。而不用依赖像Spring这样的第三方框架。