Are there anyway to disable annotation in spring4?

醉酒当歌 提交于 2021-02-05 04:48:16

问题


I have a question, maybe simple, but I can not find out the solution.

I am using spring boot and added some annotation to the code like this:

@EnableEurekaClient
@SpringBootApplication
@EnableCaching
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

But in some other environment, for example, in production environment, we want to remove EurekaClient, but I do not want to manually remove it manually for each environment, instead, I want to use environment variable or command line parameter to control the behavior. I suppose to do this way:

@EnableEurekaClient(Enabled = {EnableEureka})
@SpringBootApplication
@EnableCaching
public class MyApplication {
        public static void main(String[] args) {
            SpringApplication.run(MyApplication.class, args);
        }
}

Then I can easily start this application without touching the code.

Can anyone tell me if this is possible? If so, how can I do it?

Thanks


回答1:


You would want to work with Spring Boot Profiles. Split out the @EnableEurekaClient to another @Configuration class and also add an @Profile("eureka-client") to the class. Then when starting up the application you can set a -Dspring.profiles.active=eureka-client for the environments other than production.

Example:

@SpringBootApplication
@EnableCaching
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

@Configuration
@EnableEurekaClient
@Profile("eureka-client")
public class EurekaClientConfiguration {
}



回答2:


I prefer this method as you don't have to create an extra profile:

@Configuration
@EnableEurekaClient
@ConditionalOnProperty(name = "application.enabled", havingValue = "true", matchIfMissing = false)
public class EurekaClientConfiguration {
}


来源:https://stackoverflow.com/questions/38986067/are-there-anyway-to-disable-annotation-in-spring4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!