2015-07-02 56 views
0

我想從jointCut訪問自定義註釋值。但我找不到方法。如何訪問彈簧方面的自定義註釋值

我的示例代碼:

@ComponentValidation(input1="input1", typeOfRule="validation", logger=Log.EXCEPTION) 
public boolean validator(Map<String,String> mapStr) { 
    //blah blah 
} 

試圖訪問@Aspect類。

但是,我沒有看到任何範圍訪問值。

方式我試圖訪問下面的代碼

CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature(); 
String[] names = codeSignature.getParameterNames(); 
MethodSignature methodSignature = (MethodSignature) joinPoint.getStaticPart().getSignature(); 
Annotation[][] annotations = methodSignature.getMethod().getParameterAnnotations(); 
Object[] values = joinPoint.getArgs(); 

我沒有看到任何值返回輸入=輸入1。如何實現這一點。

+0

你能提供包括整個自定義驗證的所有代碼嗎? – Mudassar

+0

嗨,我也在我的aspectj自定義註釋學習階段。你能否給我一個演示如何使用自定義註釋?我是春季方面的新人。任何幫助將不勝感激。提前致謝。 – James

回答

1

雖然Jama Asatillayev的答案從普通的Java角度來看是正確的,但它涉及反思。

但問題是關於Spring AOP或AspectJ的,特別是使用AspectJ語法將匹配的註釋綁定到方面建議參數時更簡單和更規範的方法 - 沒有任何反射,順便說一句。

import org.aspectj.lang.JoinPoint; 
import org.aspectj.lang.annotation.Aspect; 
import org.aspectj.lang.annotation.Before; 

import my.package.ComponentValidation; 

@Aspect 
public class MyAspect { 
    @Before("@annotation(validation)") 
    public void myAdvice(JoinPoint thisJoinPoint, ComponentValidation validation) { 
     System.out.println(thisJoinPoint + " -> " + validation); 
    } 
} 
0

爲了得到值,使用如下:

你可以打電話validation.getInput1(),假設你有ComponentValidation定義註解此方法。

0

例如,如果你已經定義在註釋界面的方法象下面這樣:

@Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER}) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface AspectParameter { 
    String passArgument() default ""; 
} 

然後就可以訪問類,並且該方法中的值方面象下面這樣:

@Slf4j 
@Aspect 
@Component 
public class ParameterAspect { 

    @Before("@annotation(AspectParameter)") 
    public void validateInternalService(JoinPoint joinPoint, AspectParameter aspectParameter) throws Throwable {  
     String customParameter = aspectParameter.passArgument(); 
    } 
}