【问题标题】:BeanPostProcessor can't process bean RedisPropertiesBeanPostProcessor 无法处理 bean RedisProperties
【发布时间】: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


【解决方案1】:

好的,我知道不能使用 jasypt。 但是,看看它的源代码,它相当简单,因为您已经使用 Bean Post Processors,这是 spring / spring boot 中相当先进的东西

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

所以你会看到它有spring.factories 可以启用一些引导和自动配置。

最终你会得到代码that actually handles the encryption

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-17
    • 2012-09-03
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多