gpt4 book ai didi

java - 如何在运行时可变属性的spring-boot中启用@ConditionalOnProperty

转载 作者:行者123 更新时间:2023-12-01 04:51:00 26 4
gpt4 key购买 nike

我有两个取决于配置变量的类:

@Component
@ConditionalOnProperty("config.db")
public class DatabaseTokenStore implements TokenStore {
}

@Component
@ConditionalOnMissingBean(DatabaseTokenStore.class)
public class SimpleTokenStore implements TokenStore {
}

所以当 db 为真时, DatabaseTokenStore类在 false 时 Autowiring ,然后 SimpleTokenStore是自动接线的。问题是我可以在运行时使用 CRaSH 更改此属性.那么这个机制将不起作用。有什么方法可以在运行时更改接口(interface)的实现吗?

最佳答案

初始化TokenStore s 在启动时。并创建一个解析器以注入(inject)您需要使用它们的类。像这样:

@Component
public class HelloStoreResolver {

@Autowired
private HelloStore oneHelloStore;

@Autowired
private HelloStore twoHelloStore;

public HelloStore get() {
if (condition) {
return oneHelloStore;
} else {
return twoHelloStore;
}
}

}


@Component
public class HelloController {

@Autowired
private HelloStoreResolver helloResolver;

//annotations omitted
public String sayHello() {
return helloResolver.get().hello();
}

}

关于java - 如何在运行时可变属性的spring-boot中启用@ConditionalOnProperty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41101481/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com