I have a rest controller contains many methods
@RestController
@RequestMapping("v1/test")
public class TestRestController {
...... 100 methods (GET, POST, PATCH, etc)
}
How can I know which method is being accessed without using print
in each method?
Are there any ways to do that?
You can use Spring AOP:
package com.example;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class ExampleAspect {
@Before("execution(* com.example.TestRestController(..)")
public void log(JoinPoint joinPoint) {
System.out.println("Executing :" + joinPoint.toString());
}
}
While you can use AOP tactics noted in the other answers to log the methods, there are better approaches if all you want to do is log all of the requests and responses for the endpoints those methods implement. There are a couple ways this can be done: Use Spring's CommonRequestLoggingFilter or write your own HandlerInterceptor. Here is a nice article on the first two options.
Using Aspect Oriented Programming with Spring:
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Aspect
public class SpringAspect {
private static final Logger LOG = LoggerFactory.getLogger(SpringAspect.class);
@Before("execution(* sample.package.path.TestRestController.*(..))")
public void executedMethodsLogger(JoinPoint joinPoint) {
LOG.info("[ Executed method {} ]", joinPoint.toString());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With