如何在spring-boot上在运行时可更改属性

时间:2016-12-12 12:59:13

标签: java spring-boot

我有两个类依赖于配置变量:

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

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

所以当db为true时,{false}会自动装配DatabaseTokenStore类,然后SimpleTokenStore自动装配。问题是我可以在运行时使用CRaSH更改此属性。然后这个机制将无法工作。有没有办法在运行时更改接口的实现?

1 个答案:

答案 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();
    }

}