BeanPostProcessor 无法处理 bean RedisProperties



我使用的弹簧启动版本是2.1.5.RELEASE。 我的项目与 redis 合作。为了安全起见,我加密了我的redis密码。我在应用程序属性中设置值,如下所示:

spring.redis.password=xxx

我想在 spring bean 的 init 之前解密,所以我想更改 RedisProperties 的passowrd属性的值。所以我像这样定制一个 BeanPostProcesser:

@Component
public class PasswordBeanPostProcessor implements BeanPostProcessor {
@Autowired
private Cryptor cryptor;
@Value("${spring.redis.password}")
private String password;
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
log.info("beanName = {}",beanName);
if (bean instanceof RedisProperties) {
RedisProperties redisPropertiesBean = (RedisProperties) bean;
try {
redisPropertiesBean.setPassword(cryptor.decrypt(password));
log.debug(redisPropertiesBean.getPassword());
return redisPropertiesBean;
} catch (Exception ex) {
log.error("redis password decrypt error", ex);
throw new RuntimeException(ex);
}
}
return bean;
}
}

但是这效果不佳,当我运行我的应用程序时,没有像这样的日志打印:

beanName = redisProperties

为了确保我的applicationContext中有一个名为redisProperties的豆子,我将豆RedisProperties注入另一个 Bean.It 运行良好,我可以在RedisProperties中获得属性。

为了使我的应用程序使用加密密码成功运行,我用另一种@PostConstruct方法解密了 redis 的密码。但我觉得这样不优雅,什么是正确的方式?

谁能帮我,请

好的,我知道不能使用 jasypt。 但是,看看它的源代码,它相当简单,因为您已经使用Bean Post处理器,这是Spring/Spring boot中相当高级的东西

它的启动器(自动配置模块(可用

这里因此,您将看到它具有启用某些引导和自动配置的spring.factories

最终你会得到实际处理加密的代码。

它使用一个 bean 工厂后处理器 - 当 bean 定义准备就绪但实际的 bean 尚未创建时,它会启动。这是一个与你相关的钩子。当然,实现会有所不同,但"编排"是相同的......

最新更新