Spring AOP custom annotation example
Reference: http://www.cnblogs.com/shipengzhi/articles/2716004.html
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Ann { String value(); }
Annotation Processor public class AnnoSupport { /** * Processing * @param joinPoint AOP pointcut * @return * @throws Throwable */ public Object doSupport(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("doSupport"); try { return process(joinPoint); } catch (Throwable t) { throw t; } } /** * Processing * @param joinPoint AOP pointcut * @return * @throws Throwable */ private Object process(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("process"); Class<?> clazz = joinPoint.getTarget().getClass(); String className = clazz.getSimpleName();//Get the class name Signature signature = joinPoint.getSignature(); Method method = ((MethodSignature) signature).getMethod(); String methodName = method.getName();//Get the method name Method realMethod = clazz.getMethod(methodName, method.getParameterTypes()); if (realMethod.isAnnotationPresent(Ann.class)) { ... ... Ann ann = realMethod.getAnnotation(Ann.class);//Get annotation System.out.println("ann:" + ann.value()); } return joinPoint.proceed();//Execution method } }
spring configuration <bean id="annoSupport" class="com.test.AnnoSupport"/> <bean id="TestAnn" class="com.test.TestAnn"> </bean> <!- Register the annotation processor --> <aop:aspectj-autoproxy/> <aop:config> <aop:aspect ref="annoSupport"> <aop:pointcut id="supportMethod" expression="@annotation(com.test.Ann)"/> <aop:around pointcut-ref="supportMethod" method="doSupport"/> </aop:aspect> </aop:config>
test class public class TestAnn { @Ann("test") public String ann(String test){ return test; } public static void main(String[] args){ ApplicationContext ac = new FileSystemXmlApplicationContext("file:D:\\workspace\\src\\main\\java\\com\\test\\applicationContext.xml"); TestAnn test = (TestAnn)ac.getBean("TestAnn"); test.ann("Test ann"); } }