首页 > 解决方案 > AOP 切入点仅适用于带注释的方法

问题描述

我正在使用 AspectJ 和 Spring AOP,但我面临一个奇怪的问题,切入点仅适用于那些上面有一些注释的方法,例如 ovverride、Bean 等。切入点不适用于类的本地方法没有注释。

以下是我正在使用的配置:

@Aspect
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
//@EnableLoadTimeWeaving
public class AspectLogging {

    private static final Logger logger = LoggerFactory.getLogger(AspectLogging.class);




      @Pointcut("execution(public * *(..))")//Public 
      public void publicMethod(){};

      @Pointcut("execution(protected * *(..))")//Protected 
      public void protectedMethod(){}

      //@Pointcut("execution(* com.s4m.user.*.*(..))")
      @Pointcut("within(com.s4m.user..*)")
     // @Pointcut("@annotation(Service)")
      public void annotationPointcut(){}

      @Pointcut("execution(private * *(..))")//Protected 

      public void privateMethod(){}


    @Before("annotationPointcut() && (protectedMethod() || publicMethod()  || privateMethod())")
    public void test(JoinPoint joinpoint) {
          logger.info(joinpoint.getSourceLocation().getWithinType().getSimpleName() +" :: "+ joinpoint.getSignature().getName() + " **Entry**");
    }

}   

例如下面是同一类的方法,切入点适用于带注释的方法,但不适用于其他方法。

@Override
    public Object logout(HttpServletRequest request) {
        loggingOut(request);
        return Utility.getResponseModel(ApiConstants.SUCCESS);
    }

    public void loggingOut(HttpServletRequest request) {
        HttpSession session = request.getSession();
        RedisUser redis = redisUserRepository.findById(request.getHeader(ApiConstants.DEVICE_ID));
        if (!Util.objectIsNull(redis)) {
            deleteUserInRedis(redis);
            saveAuditTrail(ApiConstants.LOGOUT, redis.getSessionId(), redis.getName(), redis.getDeviceId(),
                    ApiConstants.OPERATION_SUCCESSFUL, true);
        }
        session.invalidate();
    }

上述方法的日志:

AC66A549C3416D3 2019-10-02 15:51:08 [http-nio-8302-exec-2] INFO  com.s4m.user.config.AspectLogging -CITI-P_003(AD PLUGIN)- UserServiceImpl :: logout**Entry**

但是这种方法没有日志,因为切入点不起作用:

public void loggingOutTest() {

    }

标签: javaspring-bootaopspring-aopspring-annotations

解决方案


Spring AOP 仅适用于 Spring bean(也可以通过注释类来创建 Spring bean)。而且您也只能拦截公共方法调用。此处仅支持 AspectJ 的有限功能。

Spring AOP 也不能使用 PS JPA 实体。


推荐阅读