'Is there any way to enable/disable a annotation by property in Spring Boot?
I have some property file like:
application.properties
enable.test.controller=true
enable.cross.origin=false
I want to enable/disable some functions based on the profile. For example, I have a controller which only opening in specific environment:
@Controller(enable=${enable.test.controller})
public class TestController() {
}
And I also want to enable/disable annotation @CrossOrigin property
@Controller
@CrossOrigin(enable=${enable.cross.origin})
public class TestController2() {
}
Is there any way to make @Annotation(enable=${property}) work?
Any suggestion will be appreciated!
Solution 1:[1]
- You can add
@ConditionalOnPropertyto your controller and specify the property based on which that controller's bean to be initialized or not.
@ConditionalOnProperty(name = "enable.test.controller", havingValue = "true")
- And for
@CrossOrigin, if you want to add this annotation to single controller, you can specify theoriginsattribute in the annotation and specify the allowed origin URLs.
OR
You can create a global CORS configuration which can be easily turned off or on using a profile. for eg. @Profile("CORS_enabled_profile")
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:8080");
}
};
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
