ServiceLoader使用和创建组件的内容区分开来

 

 

 

package com.cn.test.beanload;

 

public interface IPersonalServant {

// Process a file of commands to the servant  

    public void process(java.io.File f)  

        throws java.io.IOException;  

    public boolean can(String command);

 

}

package com.cn.test.beanload;
import java.io.File;
public class Jeeves implements IPersonalServant {
public void process(File f) {
System.out.println("Very good, sir.");
}
public boolean can(String cmd) {
if (cmd.equals("fetch tea"))
return true;
else
return false;
}
}

package com.cn.test.beanload;

 

import java.io.File;

import java.io.IOException;

import java.util.ServiceLoader;

 

public class Servant {

public static void main(String[] args)  

    throws IOException  

{  

    ServiceLoader servantLoader =  

        ServiceLoader.load(IPersonalServant.class);  

 

    IPersonalServant i = null;  

    for (IPersonalServant ii : servantLoader)  

        if (ii.can("fetch tea"))  

            i = ii;  

 

    if (i == null)  

        throw new IllegalArgumentException("No suitable servant found");  

 

    for (String arg : args)  

    {  

        i.process(new File(arg));  

    }  

}  

}

使用时需要META-INF/services/com.cn.test.beanload.IPersonalServant 文件
内容为com.cn.test.beanload.Jeeves
将项目打包成jar后,加入工程,调用Servant .

你可能感兴趣的:(ServiceLoader使用和创建组件的内容区分开来)