Use Spring @RefreshScope, @Conditional annotations to replace bean injection at runtime after a ConfigurationProperties has changed

瘦欲@ 提交于 2019-12-06 13:44:44

问题


I'm running a PoC around replacing bean injection at runtime after a ConfigurationProperties has changed. This is based on spring boot dynamic configuration properties support as well summarised here by Dave Syer from Pivotal.

In my application I have a simple interface implemented by two different concrete classes:

@Component
@RefreshScope
@ConditionalOnExpression(value = "'${config.dynamic.context.country}' == 'it'")
public class HelloIT implements HelloService {
    @Override
    public String sayHello() {
        return "Ciao dall'italia";
    }
  }

and

@Component
@RefreshScope
@ConditionalOnExpression(value = "'${config.dynamic.context.country}' == 'us'")
public class HelloUS implements HelloService {
    @Override
    public String sayHello() {
        return "Hi from US";
    }

}

application.yaml served by spring cloud config server is:

config:
  name: Default App
  dynamic:
    context:
      country: us

and the related ConfigurationProperties class:

@Configuration
@ConfigurationProperties (prefix = "config.dynamic")
public class ContextHolder {

private Map<String, String> context;
  Map<String, String> getContext() {
     return context;
}

public void setContext(Map<String, String> context) {
    this.context = context;
}

My client app entrypoint is:

@SpringBootApplication
@RestController
@RefreshScope
public class App1Application {

@Autowired
private HelloService helloService;

@RequestMapping("/hello")
public String hello() {
    return helloService.sayHello();
}

First time I browse http://locahost:8080/hello endpoint it returns "Hi from US"

After that I change country: us in country: it in application.yaml in spring config server, and then hit the actuator/refresh endpoint ( on the client app).

Second time I browse http://locahost:8080/hello it stills returns "Hi from US" instead of "ciao dall'italia" as I would expect.

Is this use case supported in spring boot 2 when using @RefreshScope? In particular I'm referring to the fact of using it along with @Conditional annotations.

来源:https://stackoverflow.com/questions/52008261/use-spring-refreshscope-conditional-annotations-to-replace-bean-injection-at

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!