Home > Enterprise >  Switch endpoint responses based on condition
Switch endpoint responses based on condition

Time:02-02

I would like to have two endpoints with the same path and decide which one is enabled on startup.

To do so I've tried using @ConditionalOnExpression() but an error is thrown as it says a mapping already exists. One endpoint uses ModelAndView while the other provides a html string so I can't add an if statement in the body of the endpoint.

Code

@ConditionalOnExpression("${my-property:false}")
@GetMapping(VIEW_INDEX)
public ModelAndView index(HttpServletRequest request) {
    ...
    return modelAndView;
}

@ConditionalOnProperty("${my-property}")
@GetMapping(VIEW_INDEX)
public String otherIndex(){
    return "/other/index";
}

Error

Ambiguous mapping. Cannot map 'controller' method 

There is already 'controller' bean method

How can I allow only one to be enabled based on a condition without there being an Ambiguous mapping?

CodePudding user response:

It will work if you try @ConditionalOnProperty or ConditionalOnExpression on 2 controllers with the same request mapping.

@RestController
@RequestMapping("/test")
@ConditionalOnProperty(value = "my-property", havingValue = "true")
public class TestTrueController {

    @GetMapping("/index")
    public String index() {
        return "Forever true!";
    }
}
@RestController
@RequestMapping("/test")
@ConditionalOnProperty(value = "my-property", havingValue = "false")
public class TestFalseController {

    @GetMapping("/index")
    public String index() {
        return "Forever false!";
    }
}

If your my-property value is true it will print "Forever true!", if false it will print "Forever false!".

  •  Tags:  
  • Related