springboot 下的多态简单实现

今天在看security 的源码时,一时好奇密码加密有很多,这些大概是怎么实现的,于是想起了java 的“多态”,于是就复习了一下。

1、先创建一个接口
public interface PasswordInterface {

    String encode(String password);

}

里面只有一个方法,就是把密码加密后返回

2、然后实现两种加密方式

创建两个实现类,都实现这个接口

public class BCryptPasswordImpl implements PasswordInterface {

    @Override
    public String encode(String password) {
        return "这是BCrypt----" + password;
    }
}

public class MD5PasswordImpl implements PasswordInterface {
    
    @Override
    public String encode(String password) {
        return "这是MD5---"+ password;
    }
}

3、关键来了,有了模型也有产品了,该拿去卖了
@Slf4j
@Component
public class PasswordConsumer {

    private PasswordInterface passwordInterface;

    public PasswordConsumer(ApplicationContext applicationContext){
        passwordInterface = ApplicationBeanUtils.getBeanOrNull(applicationContext,PasswordInterface.class);
        if(passwordInterface == null){
            passwordInterface = new MD5PasswordImpl();
        }
    }

    public void encodePassword(String password){
        String encode = this.passwordInterface.encode(password);
        log.info("========={}",encode);
    }

}

这里就是创建一个消费类,主要就是在构造方法中首先去spring容器中找这个PasswordInterface 的bean,如果没有,就new 一个默认的

4、写一个配置类,指定要用哪一个实现
@Configuration
public class PasswordConfig {

    @Bean
    public PasswordInterface passwordInterface(){
        // return new BCryptPasswordImpl();
        return new MD5PasswordImpl();
    }
}
5、测试一下
@RestController
@RequestMapping("/test")
public class TestPasswordController {

    @Autowired
    public PasswordProducer passwordProducer;

    @RequestMapping(value = "/01",method = RequestMethod.GET)
    public void test(){
        passwordProducer.encodePassword("123456");
    }

}

// 输出结果 :  =========这是MD5---123456
// 在配置类中换成 BCryptPasswordImpl 后 
// 输出结果 :  =========这是BCrypt---123456

最后这个getBean的工具类
@UtilityClass
public class ApplicationBeanUtils {

    public  <T> T getBeanOrNull(ApplicationContext applicationContext,Class<T> type) {
        String[] beanNames = applicationContext.getBeanNamesForType(type);
        return beanNames.length != 1 ? null : applicationContext.getBean(beanNames[0], type);
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值