Reputation: 16555
I have two class which depends on config variable:
@Component
@ConditionalOnProperty("config.db")
public class DatabaseTokenStore implements TokenStore {
}
@Component
@ConditionalOnMissingBean(DatabaseTokenStore.class)
public class SimpleTokenStore implements TokenStore {
}
so when db is true then DatabaseTokenStore
class is autowired when false then SimpleTokenStore
is autowired. Problem is that I can change this property in runtime with CRaSH
. Then this mechanic will not work. Is there some way how to change implement of interface in runtime ?
Upvotes: 4
Views: 1533
Reputation: 2101
Initialize both TokenStore
s on startup. And create a resolver to inject into classes where you need to work with them. Like so:
@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();
}
}
Upvotes: 1