利用springboot初始化机制三种实现策略模式的应用

面试时总被问,spring中使用了哪些设计模式,你在实际开发中又使用哪些设计模式。给他手指一个方向跟他说,这就是一个模式:go out!。

这就是一种模式:策略模式,一个接口的多个实现方式(算法)。本文梳理了使用springboot实现的三种实现策略模式的应用

我们知道,springboot应用初始化的过程是通过事件机制进行的。主要是通过 EventPublishingRunListener 在不同的初始化阶段发送不同的 SpringApplicationEvent (不同的子)事件,触发相应逻辑(这里的逻辑指class的加载)的加载和初始化。

当 ApplicationPreparedEvent 事件发送后,对于应用来讲,说明整个初始化过程已完成,也意味着所有的类已放入spring ioc 中。

这时我们就可以结合自己的业务逻辑实现策略模式的应用,我们通过以下三种方式实现策略的应用

方式一:使用ApplicationListenerContextRefreshedEvent

核心使用的是 ApplicationContext.getBeanNamesForAnnotation(Class annotationType)方法,基于注解类,获取标有指定注解类的所有实例

我们的业务逻辑是这样的:应用Api接收规则参数(authType),Api 根据authType 值的不同,使用不同的auth service,执行相应的规则业务逻辑。

public interface UserValidator<D, R> {
    String check(D data, R rule);œ
}
@Service
@Validator(authType = AuthType.B_USER)
public class BUserValidator implements UserValidator<String, String> {
    @Override
    public String check(String data, String rule) {
        System.out.println("客官,这里B端用户逻辑");
        return "";
    }
}
@Service
@Validator(authType = AuthType.C_USER)
public class CUserValidator implements UserValidator<String, String> {
    @Override
    public String check(String data, String rule) {
        System.out.println("客官,这里C端用户逻辑");
        return "";
    }
}
public enum AuthType {
    B_USER(1, "b端用户"),
    C_USER(2, "c端用户");

    public final int type;

    public final String code;

    AuthType(int type, String code) {
        this.type = type;
        this.code = code;
    }
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
@Inherited
public @interface Validator {

    AuthType authType();
}
@Component
public class AuthContainer implements Ap
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值