Spring动态选择实现类

一、需求描述

在实际工作中,我们经常会遇到一个接口及多个实现类的情况,并且在不同的条件下会使用不同的实现类,那么如何动态选择某一个实现类呢。

二、代码实现

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中方法综合了一下。以上三种方法想要使用哪一种看最近习惯即可。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring动态代理是通过JDK动态代理和CGLIB动态代理两种方式来实现的。 1. JDK动态代理 JDK动态代理是利用Java反射机制在运行时创建一个实现某一接口的代理对象。在Spring中,当一个目标实现了至少一个接口时,默认采用JDK动态代理。JDK动态代理只能代理实现接口,而不能代理没有实现接口。 示例代码: ``` public interface UserService { void addUser(); } public class UserServiceImpl implements UserService { @Override public void addUser() { System.out.println("add user"); } } public class MyInvocationHandler implements InvocationHandler { private Object target; public MyInvocationHandler(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before invoke method..."); Object result = method.invoke(target, args); System.out.println("after invoke method..."); return result; } } public static void main(String[] args) { UserService userService = new UserServiceImpl(); InvocationHandler invocationHandler = new MyInvocationHandler(userService); UserService proxy = (UserService) Proxy.newProxyInstance(userService.getClass().getClassLoader(), userService.getClass().getInterfaces(), invocationHandler); proxy.addUser(); } ``` 2. CGLIB动态代理 CGLIB动态代理是通过继承目标,生成目标的子实现代理。在Spring中,当一个目标没有实现任何接口时,采用CGLIB动态代理。CGLIB动态代理需要依赖于CGLIB库,可以在运行时动态生成代理字节码,并加载到JVM中。 示例代码: ``` public class UserService { public void addUser() { System.out.println("add user"); } } public class MyMethodInterceptor implements MethodInterceptor { private Object target; public MyMethodInterceptor(Object target) { this.target = target; } @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { System.out.println("before invoke method..."); Object result = proxy.invokeSuper(obj, args); System.out.println("after invoke method..."); return result; } } public static void main(String[] args) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(UserService.class); enhancer.setCallback(new MyMethodInterceptor(new UserService())); UserService userService = (UserService) enhancer.create(); userService.addUser(); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值