【问题标题】:Injecting a dynamic value into a bean's constructor-arg tag将动态值注入 bean 的 constructor-arg 标签
【发布时间】:2018-08-15 00:39:40
【问题描述】:

我有一个 3d 方库,它将密码作为定义为 Spring bean 的类的构造函数参数。

<bean class="com.thirdparty.CoolClass" id="coolClassId">
   <constructor-arg index="1" value="clearTextPassword" />
</bean>

但我有一个问题......安全政策禁止我使用明文密码。所以我可以设置另一个接受加密密码并解密的 bean。

@Component("decryptor") 
public class DecryptorService {

  public String decrypt(String encryptedString) { 
   ///
  }
}

无论如何,我的 XML 是否存在,以便构造函数参数通过将加密属性传递给此 DecryptorService 来获取其值?

【问题讨论】:

  • 如果不是明文密码。那你在哪里配置你的密码呢?它必须在正确的地方?
  • 当然——我们的属性有一个加密密码,然后我们解密并传入。这就是“DecryptorService”的重点

标签: java spring autowired


【解决方案1】:

假设您对自己的代码具有写入权限。 使用@Bean 方法创建一个@Configuration 类,如下所示

@Configuration
class ApplicationConfig {
    @Autowired DecryptorService decryptorService;
    @Autowired Properties props;

    @Bean
    public String clearTextPassword() {
        decryptorService.decrypt(props.getEncryptedPassword());
    }
}

然后更改您的 bean 定义以使用 ref

<bean class="com.thirdparty.CoolClass" id="coolClassId">
   <constructor-arg index="1" ref="clearTextPassword" />
</bean>

【讨论】:

    猜你喜欢
    • 2020-02-27
    • 2011-07-06
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 2017-02-27
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多