定义接口
package com.hiwzc.myspi; public interface Demo { void dosomething(); }
提供两种模拟实现
package com.hiwzc.myspi.impl; import com.hiwzc.myspi.Demo; public class DemoAImpl implements Demo{ @Override public void dosomething() { System.out.println("A"); } }
package com.hiwzc.myspi.impl; import com.hiwzc.myspi.Demo; public class DemoBImpl implements Demo { @Override public void dosomething() { System.out.println("B"); } }
META-INF/services/com.hiwzc.myspi.Demo文件,提供一种实现:
com.hiwzc.myspi.impl.DemoAImpl
代码调用
package com.hiwzc.myspi; import java.util.ServiceLoader; public class Main { public static void main(String[] args) { ServiceLoader<Demo> loader = ServiceLoader.load(Demo.class); for (Demo demo : loader) { demo.dosomething(); } } }
时间: 2024-10-30 20:13:58