简体   繁体   中英

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!

  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");
            }
        };
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM