hudi
hudi

Reputation: 16555

How to enable @ConditionalOnProperty in spring-boot on runtime changeable property

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

Answers (1)

Martin Hansen
Martin Hansen

Reputation: 2101

Initialize both TokenStores 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

Related Questions