Is it possible to create a method level @RequestMapping
that is only mapped if a certain profile is active?
I know it is possible to have the controller created only if a specific profile is active, but I am referring specifically to method @RequestMapping
s at the method level
annotation. RequestMapping annotation is used to map web requests onto specific handler classes and/or handler methods. @RequestMapping can be applied to the controller class as well as methods.
The Spring MVC @RequestMapping annotation is capable of handling HTTP request methods, such as GET, PUT, POST, DELETE, and PATCH. By default, all requests are assumed to be of HTTP GET type.
RequestMapping With Request Parameters @RequestMapping allows easy mapping of URL parameters with the @RequestParam annotation. We are then extracting the value of the id parameter using the @RequestParam(“id”) annotation in the controller method signature.
The @RequestMapping annotation can be applied to class-level and/or method-level in a controller.
No. Profiles affect only bean creation, not method. So you either create the whole controller or no.
Your options:
1) Create a controller with the methods that have to be available only for the given profile.
2) If you don't want to create a dedicated controller for the given method that has to be created only for a given profile you can programmatically check the active profiles and return 404 or whatever you want.
@Autowired
Environment environment;
public boolean isMyProfileActive() {
for (final String profileName : environment.getActiveProfiles()) {
if("mySpecificProfile".equals(profileName)) return true;
}
return false;
}
@RequestMapping(...)
public ResponseEntity<?> myMethod(){
if(isMyProfileActive()) return new ResponseEntity(HttpStatus.NOT_FOUND);
//the rest of the code for the method
}
No.
Taken from spring docs:
The @Profile annotation may be used in any of the following ways:
- as a type-level annotation on any class directly or indirectly annotated with @Component, including @Configuration classes
- as a meta-annotation, for the purpose of composing custom stereotype annotations
- as a method-level annotation on any @Bean method
If a @Configuration class is marked with @Profile, all of the @Bean methods and @Import annotations associated with that class will be bypassed unless one or more of the specified profiles are active. This is very similar to the behavior in Spring XML: if the profile attribute of the beans element is supplied e.g., , the beans element will not be parsed unless profiles 'p1' and/or 'p2' have been activated. Likewise, if a @Component or @Configuration class is marked with @Profile({"p1", "p2"}), that class will not be registered/processed unless profiles 'p1' and/or 'p2' have been activated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With