Home > Back-end >  Is there any way to enable/disable a annotation by property in Spring Boot?
Is there any way to enable/disable a annotation by property in Spring Boot?

Time:05-01

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!

CodePudding user response:

  1. You can add @ConditionalOnProperty to 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")
  1. And for @CrossOrigin, if you want to add this annotation to single controller, you can specify the origins attribute 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");
            }
        };
    }
  • Related