一、需求描述
在实际工作中,我们经常会遇到一个接口及多个实现类的情况,并且在不同的条件下会使用不同的实现类,那么如何动态选择某一个实现类呢。
二、代码实现
1.根据ApplicationContext的getBeansOfType和自定义注解实现
spring上下文工具类ApplicationContextUtil
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextUtil implements ApplicationContextAware {
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextUtil.applicationContext = applicationContext;
}
public static <T> T getBean(Class<T> type) {
return applicationContext.getBean(type);
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
}
AdapterFactory 实现类选择器工厂
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.StringUtils;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class AdapterFactory {
private static final ConcurrentMap<String, Object> INSTANCE_MAP = new ConcurrentHashMap<>();
public static <T> T getInstance(Class<T> type, String source) {
Map<String, T> maps = ApplicationContextUtil.getApplicationContext().getBeansOfType(type);
if (maps.isEmpty()) {
throw new IllegalArgumentException("找不到对应的实例type=" + type.getName() + ";source=" + source);
}
String key = source + "_" + type.getName();
Object t = INSTANCE_MAP.get(key);
if (t != null) {
return type.cast(t);
}
for (T obj : maps.values()) {
Adapter adapter = AnnotationUtils.findAnnotation(obj.getClass(), Adapter.class);
if (adapter != null && contains(adapter.value(), source)) {
T instance = type.cast(obj);
INSTANCE_MAP.putIfAbsent(key, instance);
return instance;
}
}
throw new IllegalArgumentException("找不到对应的实例type=" + type.getName() + ";source=" + source);
}
private static boolean contains(String[] sourceArr, String source) {
if (sourceArr == null || StringUtils.isEmpty(source)) {
return false;
}
for (String s : sourceArr) {
if (source.equals(s)) {
return true;
}
}
return false;
}
}
自定义注解 Adapter
import org.springframework.core.annotation.AliasFor;
import java.lang.annotation.*;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Adapter {
@AliasFor(attribute = "platform")
String[] value() default {};
@AliasFor(attribute = "value")
String[] platform() default {};
}
接口与实现类
public interface TestUserService {
TestUser getTestUser(String nick, String appKey);
}
@Service
@Slf4j
@Adapter("6870415788675974663")
public class TestUserAImpl implements TestUserService {
TestUser getTestUser(String nick, String appKey){
// 实现类的业务逻辑
}
}
@Service
@Slf4j
@Adapter("30250779")
public class TestUserBImpl implements TestUserService {
TestUser getTestUser(String nick, String appKey){
// 实现类的业务逻辑
}
}
使用demo
public TestUser getTestUser(UserInfo userInfo, AdInformation adInformation, String appKey) {
TestUser user = userInfo.getTestUser();
if (user == null) {
TestUserService testUserService = null;
try {
//通过appkey自定选择实现类,这个sppkey的值就是实现类上@Adapter注解里的值
testUserService = AdapterFactory.getInstance(TestUserService.class, appKey);
} catch (Exception e) {
log.error("getInstance error", e);
}
if (testUserService != null) {
user = testUserService.getTestUser(adInformation.getUserNick(), appKey);
}
}
return user;
}
2.实现InitializingBean将所有注入的接口放到到一个map中,然后通过对应的key获取所需的实现类
接口和实现类
public interface ITestService {
long getPrintNum(User user, int count, String printType);
}
@Service("qnTestService")
public class QnTestService implements ITestService {
@Override
public long getPrintNum(User user, int count, String printType) {
//业务逻辑
}
}
@Service("pddTestService")
public class PddTestService implements ITestService {
@Override
public long getPrintNum(User user, int count, String printType) {
//业务逻辑
}
}
@Service
public class TestService implements ITestService {
@Override
public long getPrintNum(User user, int count, String printType) {
//通过接口选择器动态选择某一个接口实现类
ITestService testService = ServiceCreater.getTestService(user.getEnumPlatform().getValue());
return testService.getPrintNum(user, count, printType);
}
}
接口选择器
@Component
public class ServiceCreater implements InitializingBean {
@Resource(name = "pddTestService")
private ITestService pddTestService;
@Resource(name = "qnTestService")
private ITestService qnTestService;
private static Map<String, ITestService> testServiceMap = new HashMap<>();
public static ITestService getTestService(String platform) {
return testServiceMap.get(platform);
}
@Override
public void afterPropertiesSet() {
testServiceMap.put("QN", qnTestService);
testServiceMap.put("PDD", pddTestService);
}
}
使用demo
@Controller
public class TestController{
@Resource
private ITestService testService;
@ResponseBody
@RequestMapping(value = "/test")
public Object test(HttpServletRequest request) {
//controller中通过注解注入的方式使用的TestService这个实现类,然后该实现类会执行getPrintNum方法,方法里通过实现类选择器选择具体的实现子类去实现具体的业务逻辑
testService.getPrintNum(user, count, printType);
}
}
3.通过ApplicationContext的getBeansOfType获取实现类然后将实现子类放到map中,然后使用的时候通过key来动态获取实现子类
实现代码就不粘贴了,其实就是将1,2中方法综合了一下。以上三种方法想要使用哪一种看最近习惯即可。