我有两个类依赖于配置变量:
@Component
@ConditionalOnProperty("config.db")
public class DatabaseTokenStore implements TokenStore {
}
@Component
@ConditionalOnMissingBean(DatabaseTokenStore.class)
public class SimpleTokenStore implements TokenStore {
}
所以当db为true时,{false}会自动装配DatabaseTokenStore
类,然后SimpleTokenStore
自动装配。问题是我可以在运行时使用CRaSH
更改此属性。然后这个机制将无法工作。有没有办法在运行时更改接口的实现?
答案 0 :(得分:0)
在启动时初始化两个TokenStore
。并创建一个解析器以注入您需要使用它们的类。像这样:
@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();
}
}