今天在看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);
}
}