Java 如何在运行时可更改属性的spring引导中启用@ConditionalOnProperty
我有两个依赖于配置变量的类:Java 如何在运行时可更改属性的spring引导中启用@ConditionalOnProperty,java,spring-boot,Java,Spring Boot,我有两个依赖于配置变量的类: @Component @ConditionalOnProperty("config.db") public class DatabaseTokenStore implements TokenStore { } @Component @ConditionalOnMissingBean(DatabaseTokenStore.class) public class SimpleTokenStore implements TokenStore { } 因此,当db为tr
@Component
@ConditionalOnProperty("config.db")
public class DatabaseTokenStore implements TokenStore {
}
@Component
@ConditionalOnMissingBean(DatabaseTokenStore.class)
public class SimpleTokenStore implements TokenStore {
}
因此,当db为true时,则自动连接
DatabaseTokenStore
类;当db为false时,则自动连接SimpleTokenStore
。问题是我可以在运行时使用CRaSH
更改此属性。那么这个机修工就不行了。有什么方法可以在运行时更改接口的实现吗?在启动时同时初始化TokenStore
s。并创建一个解析器,将其注入到需要使用它们的类中。像这样:
@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();
}
}
似乎没有道理?您正在创建单例(默认范围)对象。因此,当应用程序启动时,您的bean只创建一次。您将只有一个TokenStore。我对您想要实现的目标感到困惑。您可以简单地将这两个bean初始化为单例,使用
getTokenStore()
方法创建一个自定义类,在运行时检查您的属性值。然后将这个“解析器类型”类注入到您想要使用TokenStore
s的地方。我不知道spring boot能够确定运行时条件注入