在META-INF/services目录下创建配置文件,文件名称为接口全名称,文件的内容每一行为一个子类全名,根据配置内容加载实现类,目录结构图
package com.learn.base;
public interface UserService {
void eat();
}
package com.learn.base;
public class UserServiceImpl implements UserService {
@Override public void eat() {
System.out.println("UserServiceImpl.eat");
}
}
package com.learn.base;
public class UserServiceImpl2 implements UserService {
@Override public void eat() {
System.out.println("UserServiceImpl2.eat");
}
}
核心代码
package com.learn.base;
import java.util.ServiceLoader;
public class ServiceLoaderT {
public static void main(String[] args) {
ServiceLoader<UserService> serviceLoader = ServiceLoader.load(UserService.class);
for(UserService l:serviceLoader){
l.eat();
}
}
}