How to dynamically change the value of the property being passed on @CondtionalOnProperty in Springboot?

Viewed 592

I have a requirement where i need to switch spring beans at runtime. I am thinking of using @ConditionalOnProperty to achieve that but i also need to create a rest endpoint which dynamically changes this property?

I am not sure how to create the rest endpoint. Can someone please recommend?

public interface myInterface {}
@Service
@ConditionalOnProperty(value = "is.new.service", havingValue="true")
public class serviceA implements myInterface{}
@Service
@ConditionalOnProperty(value = "is.new.service", havingValue="false")
public class serviceB implements myInterface{}
    
    public class Myinitializer {
    private myInterface  myA;
    
    public myinitializer(myInterface  myA){
    this.myA = myA;  
    }
}

application.properties

is.new.service = true

Now I also need to create a rest endpoint which can change the value is.new.service dynamically based on the value being passed in the request. Can someone please recommend how to achieve it?

1 Answers

If you are planning to create rest endpoint, conditional property would not be the right choice. The usage of conditional property as mentioned in the code sample here creates a bean during initialization itself. And changing the property value during runtime also doesnt affect the beans as they were already initialized earlier.

Considering that you need to get a bean based on the request, add a query param to accept a boolean value and choose the bean based on the boolean (You can also create your condition appropriately in case you have further calculations to do). Sample endpoint:

@RequestMapping(value = "/endpoint", method = RequestMethod.GET)
@ResponseBody
public Foo getFoo(@RequestParam boolean conditon)
{ 
    private myInterface  myA;
    if(condition) {
       myA = context.getBean("serviceA");
     } else {
       myA = context.getBean("serviceB");
     }
     
    .......
}
Related