I am new to Spring and AOP. I am trying this simple thing where I have created a custom annotation which when placed before any method should execute some code. This is the annotation I created
// Declares a custom annotation that validates json
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface JsonSchemaAnnotation {
}
Next I created the Spring Aspect class which holds the logic
@Aspect
public class UpdateUIMetadataInterceptor {
@Pointcut("execution(public * com.fico.cardinal.cm.*.*(..))")
public void anyPublicMethod() {
System.out.println("Running");
}
@Before("anyPublicMethod() && @annotation(jsonSchemaAnnotation)")
public void validateJson(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("Running");
}
}
And this is my simple test class
public class ValidationTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring/configuration.xml");
String jsondata = "{\"id\": \"EXPENSE_REPORT\",\"properties\": {\"transactionType\": \"EXPENSE_REPORT\"},\"sections\": []} ]}";
ValidationTest test = new ValidationTest();
test.jsonValidationTest("dummy", jsondata);
((AbstractApplicationContext) context).close();
}
@JsonSchemaAnnotation
public void jsonValidationTest(String dummy, String jsondata) {
System.out.println("Success");
}
The problem is my spring aop never gets triggered. I have included a bean in my configuration.xml
<aop:aspectj-autoproxy>
<aop:include name="UpdateUIMetadataInterceptor" />
</aop:aspectj-autoproxy>
<bean id="updateUI" class="com.fico.cardinal.cm.interceptor.UpdateUIMetadataInterceptor" />
Can anyone point out what I am missing?
You have several problems with your code:
- You should create your
ValidationTestobject as a bean managed by Spring and not using new <aop:include name="UpdateUIMetadataInterceptor" />should be<aop:include name="updateUI"/>; you can actually just stick with<aop:aspectj-autoproxy/>for simplicity hereProceedingJoinPointis not supported for before aspects, so remove it; you can useJoinPointinstead if you need access to argumentsJsonSchemaAnnotation jsonSchemaAnnotationparameter should be present forvalidateJsonmethod of your aspect, as pointed out by frant.hartm
I think you need either fully qualified name or a parameter in the method:
FQN:
@Before("anyPublicMethod() && @annotation(your.package.JsonSchemaAnnotation)")
public void validateJson(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("Running");
}
Parameter:
@Before("anyPublicMethod() && @annotation(jsonSchemaAnnotation)")
public void validateJson(ProceedingJoinPoint pjp, JsonSchemaAnnotation jsonSchemaAnnotation ) throws Throwable {
System.out.println("Running");
}
Source: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html#aop-pointcuts
(and you also need to use the bean, as Dmitry Kuskov pointed out
来源:https://stackoverflow.com/questions/31986336/spring-aop-pointcut-does-not-trigger