场景:MyServiceImpl1 和 MyServiceImpl2 都实现了 MyService接口
@Service public class MyServiceImpl1 implements MyService { @Override public Type getType() { return Type.ONE; } // ... } @Service public class MyServiceImpl2 implements MyService { @Override public Type getType() { return Type.TWO; } // ... }
方式1,通过set注入
@Component public class InitializeTest { private static Map<Type, MyService> myServiceMap = new LinkedHashMap<>(); @Autowired(required = false) public void setMyServices(List<MyService> services) { myServiceMap.clear(); for (MyService service : services) { myServiceMap.put(service.getType(), service); } } public static MyService getMyServiceByType(Type type) { return myServiceMap.get(type); } }
方式2, 通过反射获取同一包下的,都实现了MyService接口的实现类
@Component public class MyCommandRunner implements CommandLineRunner { @Autowired private ApplicationContext applicationContext; private static Map<Type, MyService> myServiceMap = new LinkedHashMap<>(); @Override public void run(String... args) { // MyCommandRunner 与实现了MyService接口的实现类位于同一包下 Reflections reflections = new Reflections(this.getClass().getPackage().getName()); Set<Class<? extends MyService>> myClasses = reflections.getSubTypesOf(MyService.class); for (Class<? extends MyService> myClass : myClasses) { MyService myService = applicationContext.getBean(monitor); myServiceMap.put(myService.getType(), myService); } } public static MyService getMyServiceByType(Type type) { return myServiceMap.get(type); } }