【发布时间】:2023-01-31 08:28:48
【问题描述】:
我有一个带有构造函数的 bean,如下所示。 password 参数是从占位符 my.password 解析而来的,默认值为 DEFAULT。如果传递了 DEFAULT 的值,则会记录一条警告。注意 - 此 Bean 包含在导入的第三方库中。
@Bean
public class EncryptionBean {
public EncryptionBean(@Value("${my.password}") String password) {
if "DEFAULT".equals(password) {
// log warning message
} else {
// do stuff with the password
}
}
}
密码是在启动时使用客户端 SDK 从外部系统检索的。此 SDK 对象本身作为 Bean 提供(也来自第三方库)。检索密码后,我将其设置为上述EncryptionBean 的系统属性,以便在实例化时访问:
@Configuration
public class MyConfiguration {
@Autowired
public SDKObject sdkObject;
@PostConstruct
public void init() {
System.setProperty("my.password", sdkObject.retrievePassword());
// @Value("${my.password"}) should now be resolvable when EncryptionBean is instantiated
}
}
但是,EncryptionBean 仍在为 my.password 实例化,值为 DEFAULT。我想知道 @PostConstruct 中的 System.setProperty 是否可能在 Spring 已经实例化 EncryptionBean 的实例之后执行?
如果是这样,有没有办法保证在 Spring 实例化 EncryptionBean 之前设置此属性?我发现 @DependsOn 是一种控制 Spring 实例化 Beans 的顺序的方法,但由于 EncryptionBean 来自第三方库,我无法使此注释起作用。
【问题讨论】:
标签: java spring-boot