Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot - @ConditionalOnExpression for @RestController

Tags:

java

rest

spring

I want to enable/disable a @RestController based on configuration, in order achieve it i'm trying to use the @ConditionalOnExpression annotation.

Using a static hardcoded value is working just fine:

@RestController
@ConditionalOnExpression("true")
public class MyRestController {

    @RequestMapping("/hi")
    public String hi() {
        return "hi";
    }
}

Yet, using a dynamic property value within a SpEL expression always results in not loading the @RestController:

@RestController
@ConditionalOnExpression("${my.rest.controller.enabled:false}")
public class MyRestController { ... }

Would really appreciate any ideas/best practices to resolve this.

like image 738
ranweiz Avatar asked Oct 29 '14 14:10

ranweiz


People also ask

Can we replace @RestController with @controller?

In simple words, @RestController is @Controller + @ResponseBody. So if you are using latest spring version you can directly replace @Controller with @RestController without any issue.

Is @RestController a spring boot annotation?

Spring RestController annotation is a convenience annotation that is itself annotated with @Controller and @ResponseBody . This annotation is applied to a class to mark it as a request handler. Spring RestController annotation is used to create RESTful web services using Spring MVC.

What is the annotation used for RestController?

RestController: RestController is used for making restful web services with the help of the @RestController annotation. This annotation is used at the class level and allows the class to handle the requests made by the client.

What is the use of @RestController in spring boot?

Spring 4.0 introduced the @RestController annotation in order to simplify the creation of RESTful web services. It's a convenient annotation that combines @Controller and @ResponseBody, which eliminates the need to annotate every request handling method of the controller class with the @ResponseBody annotation.


1 Answers

To verify that a property in Spring Cloud Config is not provided, I used the following expression:

  /**
   * @return The Jms Template for sending the messages to the queue.
   */
  @Bean(name = "jmsTemplate")
  @ConditionalOnExpression("!'${jsk.messaging.jms.queue}'.isEmpty()")
  public JmsTemplate jmsTemplateForQueues() {
    JmsTemplate jmsTemplate = new JmsTemplate();
    CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(activeMQConnectionFactory());
    jmsTemplate.setConnectionFactory(cachingConnectionFactory);
    return jmsTemplate;
  }
like image 165
Marcello de Sales Avatar answered Oct 31 '22 02:10

Marcello de Sales