一个接口有多个实现类 , 通过实现ApplicationContextAware将所有的实现类管理起来 , 使用的时候传入实现类的容器名称调用。
@Autowired
private InterfaceServiceLocator locator;
// 获取接口指定的实现类( Spring容器中默认名称是类名首字母小写 )
InterfaceService service = locator.getService("interfaceServiceImpl1");
// 接口
public interface InterfaceService {
}
// 实现类1
public class InterfaceServiceImpl1 implements InterfaceService {
}
// 实现类2
public class InterfaceServiceImpl2 implements InterfaceService {
}
package cn.com.baidu.filter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/**
* explain:获取实现类
* @author cbc
* @date 2021/1/5
*/
@Component
public class InterfaceServiceLocator implements ApplicationContextAware {
/**
* 用于保存接口实现类名及对应的类
*/
private Map<String, InterfaceService> map = new HashMap<String, InterfaceService>();
/**
* 获取应用上下文并获取相应的接口实现类
* @param applicationContext
* @throws BeansException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
//根据接口类型返回相应的所有bean
map = applicationContext.getBeansOfType(InterfaceService.class);
}
/**
* 获取所有实现集合
* @return
*/
public Map<String, IShopAuditLogUpdateService> getMap() {
return map;
}
/**
* 获取对应实现类
* @param key
* @return
*/
public IShopAuditLogUpdateService getService(String key) {
return map.get(key);
}
}