【问题标题】:Collect all the method names in the flow of Spring MVC收集Spring MVC流程中的所有方法名
【发布时间】:2017-07-23 00:08:51
【问题描述】:

我是 Spring MVC 的新手。我正在开发一个应用程序,在进入登录控制器之前,它会在安全控制器中执行一些过程。我不知道登录时访问了我代码中的所有方法。

所以我想知道是否有办法在登录时记录应用程序流中的所有方法?

请帮帮我。

谢谢。

【问题讨论】:

  • @CollinD 更正了这个问题。对不起。您能否告诉我是否有办法收集应用程序访问的所有方法?
  • 查看我的answer 了解类似要求

标签: java spring spring-mvc spring-security


【解决方案1】:

您可以使用面向方面的编程。 Spring 使用代理提供了自己的 AOP 实现(尽管有一些限制 - 例如,您不能建议私有方法)。作为替代方案,您也可以使用 AspectJ。无论如何,这里是使用 Spring AOP 来建议应用程序的任何公共方法的示例代码:

@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();
}

@Around(value= "publicMethod()")注解使用自定义切入点,定义为带有@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
}

要使一切正常,您需要在配置类中添加@EnableAspectJAutoProxy 注释:

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

注意:注意不要给你的 AOP 类提供建议——这会让事情变得有点混乱。您可以将 AOP 类放在单独的包中(例如 your.app.aop)或在 potcut 定义中使用排除(!within(your.app.aop..*))。

请阅读一些关于 AOP 的文章以更好地理解这个想法。官方 Spring 文档应该没问题 - https://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html

【讨论】:

    【解决方案2】:

    最干净和最正确的方法是在您的应用程序中实现正确的日志记录。这样,您现在就可以完全了解方法的流程了。

    否则,您始终可以使用Thread.currentThread().getStackTrace() 找出访问了哪些方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-20
      • 2019-06-05
      • 1970-01-01
      • 2020-11-16
      • 2016-10-22
      • 2015-09-05
      • 2021-09-15
      • 2021-10-20
      相关资源
      最近更新 更多