2 years ago

#66558

test-img

Aaron

Spring Cloud Config - @ConditionalOnProperty and @Configuration behavior

I'm having some issues with @ConditionaOnProperty and @Configuration behavior not being updated based on the changes in the application properties (config file).

Here's what I have

  1. Configuration

    @Configuration
    public class RandomRestConfig {
    
        @Value("${external.message.root.uri}")
        private String rootUri;
    
        @Bean
        @RefreshScope
        public RestTemplate randomRestTemplate() {
            return new RestTemplateBuilder()
            .rootUri(rootUri)
            .build();
        }
    }
    
  2. Conditional service

    @Service
    @RefreshScope
    @ConditionalOnProperty(value = "external.message.enabled", havingValue = "true")
    public class RandomRestService {
    
        @Autowired
        @Qualifier("randomRestTemplate")
        private RestTemplate restTemplate;
    
        public String getMessageFromService() {
            final var response = restTemplate.getForEntity("/trips/trip-text", String.class);
            return response.getBody();
        }
    }
    
  3. Usage via controller

    @RefreshScope
    @RestController
    public class MessageRestController {
    
        @Value("${message: No message found}")
        private String message;
    
        private RandomRestService randomRestService;
    
        public MessageRestController(Optional<RandomRestService> optionalRestService) {
            optionalRestService.ifPresent(service -> this.randomRestService = service);
        }
    
        @GetMapping("/external-message")
        String getExternalMessage() {
            if (randomRestService == null) {
            throw new RuntimeException("Invalid request - rest is disabled");
            }
    
            return randomRestService.getMessageFromService();
        }
    }
    

Now, what I'm trying to achieve are

  1. Change the value of the rootUri. I changed it in the config file but it didn't take effect, the old URI is still in effect.

  2. Change the value of external.message.enabled from false to true, but the service is still null in MessageRestController. I was expecting that the bean will be updated.

Now, with both scenarios, I manually triggered the actuator /refresh endpoint and both properties were visible in the response.

    [
        "config.client.version",
        "external.message.root.uri",
        "external.message.enabled"
    ]

Am I missing something? Or is it possible at all? Thank you!

spring-cloud

spring-cloud-config

0 Answers

Your Answer

Accepted video resources