Spring AOP - 拦截其祖先有注释的类

时间:2013-06-04 12:11:17

标签: java spring aop

我有以下层次结构:

@Validated
public class BaseResource 

public class DeviceResource extends BaseResource

@Validated注释如下:

package com.redbend.validation.annotation;

import static java.lang.annotation.ElementType.TYPE;

import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.inject.Scope;



@Scope
@Target(TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Validated {

}

我有一个Spring Aspect,有以下建议:

    package com.redbend.validation.aspect;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;

import javax.validation.constraints.NotNull;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.redbend.exceptions.EExceptionMsgID;
import com.redbend.exceptions.runtime.MissingMandatoryParameterException;
import com.redbend.validation.annotation.MandatoryOneOfParams;
import com.redbend.validation.annotation.MandatoryParams;
import com.redbend.validation.annotation.NotEmpty;
import com.redbend.validation.annotation.OneOfParamsForValue;
import com.redbend.validation.annotation.OneOfParamsForValueMap;
import com.redbend.validation.annotation.ParamsForValue;
import com.redbend.validation.annotation.ParamsForValueMap;

@Aspect
@Component
@Order(2)


public class ValidationInterceptor {

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

    public ValidationInterceptor() {
        // TODO Auto-generated constructor stub
    }

    @Before("within(com.redbend..*) && @within(com.redbend.validation.annotation.Validated) ")
    public void validate(JoinPoint joinPoint) throws Exception {
        validateParams(joinPoint);
    }

当我在DeviceResource中调用某个方法时,它不会被该方面捕获,即使它认为它继承自BaseResource注释为@Validated,并且@Validated是用@Inherited注释 当我使用DeviceResource注释@Validated时,它可以正常工作。如何在不使用DeviceResource注释的情况下在@Validated中截取我的方法?

谢谢,

阿米尔

2 个答案:

答案 0 :(得分:2)

within(@com.redbend.validation.annotation.Validated)

不正确,应该是

@within(com.redbend.validation.annotation.Validated)

答案 1 :(得分:0)

我最终通过改变我方面的切入点表达来解决它:

@Before("within(com.redbend..*) && within(@com.redbend.validation.annotation.Validated *)")

我仍然不知道为什么它之前没有用或为什么@within(com.redbend.validation.annotation.Validated) 没用......