Collect all the method names in the flow of Spring

2019-09-14 13:47发布

I am new to Spring MVC . I am working on an application where before going to the login controller it does some process in security controller. I dont know to which all methods in my code is accessed while logging in.

So i am trying to know if there is a way to log all the methods in the flow of application while logging in?

Please help me.

Thanks.

2条回答
Root(大扎)
2楼-- · 2019-09-14 14:04

You can use Aspect Oriented Programming. Spring provides its own implementation of AOP using proxies (there are some limitations, though - e.g. you can't advice private methods). As an alternative, you can also use AspectJ. Anyway, here is the example code using Spring AOP to advice any public method of your application:

@Around(value = "publicMethod()")
public Object logMethod(ProceedingJoinPoint joinPoint) {
    // TODO: access method details using joinPoint
    // e.g. access the public method name
   MethodSignature methodSignature = (MethodSignature) joinPoint
                    .getSignature();
   // do anything you want with the method's name, for instance log it
   LOGGER.debug("Public method invoked: {}", methodSignature.getMethod().getName());

   return joinPoint.proceed();
}

The @Around(value= "publicMethod()") annotation uses a custom pointcut, which is defined as method annotated with @Pointcut:

@Pointcut("execution(public * your.app.package.*.*(..)) ")
private void publicMethod() {
    // this is just a declaration required by AOP framework - we don't need to insert any code here
}

To make everything work, you need to add @EnableAspectJAutoProxy annotation to your config class:

@ComponentScan(value = "your.app.package")
@Configuration
@EnableAspectJAutoProxy
public class TestConfig
{
}

Note: watch out to not advice your AOP classes - this would mess things a bit. You can place AOP classes in separate package (e.g. your.app.aop) or use exclusion in potcut definition (!within(your.app.aop..*)).

Please, read some articles regarding AOP to better understand the idea. Official Spring documentation should be fine - https://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html.

查看更多
贼婆χ
3楼-- · 2019-09-14 14:17

The cleanest and most proper way to do this is to have proper logging implemented in your application. That way, you would now exactly the flow of the methods.

Otherwise, you can always use Thread.currentThread().getStackTrace() to figure out which methods were accessed.

查看更多
登录 后发表回答