【发布时间】:2020-06-16 09:59:17
【问题描述】:
我使用的 spring boot 版本是 2.1.5.RELEASE。 我的项目使用redis。为了安全,我加密了我的redis密码。我在我的application.properties中设置了如下值:
spring.redis.password=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
我想在spring bean的初始化之前解密,所以我想改变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 的bean,我将bean RedisProperties 注入另一个Bean。它运行良好,我可以在RedisProperties 中获取属性。
为了让我的应用程序使用加密密码运行成功,我用别人的@PostConstruct方法解密redis的密码。但是我认为这种方式不优雅,正确的方式是什么?
谁能帮帮我,拜托
【问题讨论】:
-
我认为你应该遵循@MarkBramnik 的建议,我正要写同样的答案
-
@Mark Bramnik 谢谢你的帮助。我已经浏览过这个页面,但是在我公司,加密方式已经指定,我不能使用 jasypt。我也想知道为什么我的 BeanPostProcesser 没有在这个 bean 中调用
RedisProperties
标签: spring spring-boot spring-autoconfiguration