Search code examples
spring-mvcaspect

Spring MVC Aspect Conditional


I have a Aspect running for Logging with custom annotation @Loggable. I want that the aspect run only when it is in testing environment. hence i tried to have a key value pair in application.yaml file.

But the condition does not work. Please Help Me

Below is the code:

@Aspect
@Component
@ConditionalOnExpression("${test.enable_loggable:true}")
public class LoggingAspect {

private final Logger logger = LoggerFactory.getLogger(this.getClass());

@Around("@annotation(Loggable)")
public Object around(ProceedingJoinPoint point) {
  long start = System.currentTimeMillis();
}

My Config is :

test:
    enable_loggable: true

I also tried with below conditions:

@ConditionalOnExpression("'${test.enable_loggable}' == 'local'")
@ConditionalOnExpression("${test.enable_loggable:false}")

Nothing works


Solution

  • One option is to use Spring Profiles. This relies on Spring's Environment abstraction and allows you to indicate which components are to be used in which environment - i.e., based on which profiles are active in the given environment.

    Documentation is here (or here for Spring Boot). But essentially you would use the @Profile annotation to specify when (i.e., in which environment) a configuration class is active, such as:

    @Configuration
    @Profile("dev")
    @Aspect
    @Component
    @ConditionalOnExpression("${test.enable_loggable:true}")
    public class LoggingAspect {
    
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
      @Around("@annotation(Loggable)")
      public Object around(ProceedingJoinPoint point) {
        long start = System.currentTimeMillis();
      }
    }
    

    The idea is you can make beans "environment aware". For example, depending on where the application is running, the appropriate configuration classes will be picked up (e.g., "dev", "staging", "prod" or whatever you specify).

    As described in the documentation, there are multiple ways to activate a profile. But perhaps the most straightforward is to use the spring.profiles.active Environment property. Profile annotated classes will be picked up if they match that property's value:

    spring.profiles.active=dev