【问题标题】:AOP pointcut is only working for methods which are annotated [duplicate]AOP切入点仅适用于带注释的方法[重复]
【发布时间】:2020-01-31 16:47:43
【问题描述】:

我正在使用 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() {

    }

【问题讨论】:

    标签: java spring-boot aop spring-aop spring-annotations


    【解决方案1】:

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

    附: JPA 实体也不能被 Spring AOP 使用。

    【讨论】:

    【解决方案2】:

    Spring AOP 只能识别 Spring bean。如果您想使用 JPA 实体等其他对象,请尝试添加 AspectJ 依赖项: https://mvnrepository.com/artifact/org.aspectj/aspectjrt

    【讨论】:

    • 好的,我已经添加了其他依赖项,我不再使用 Spring AOP,只使用 AspectJ,我需要更改上面的任何配置吗?因为加了aspectj依赖后还是不行。
    猜你喜欢
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多