Spring AOP自定义注解样例

Spring AOP自定义注解样例

参考:http://www.cnblogs.com/shipengzhi/articles/2716004.html 

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Ann {

    String value();

}
注解处理器
public class AnnoSupport {
    /**
     * 处理过程
     * @param joinPoint AOP切入点
     * @return
     * @throws Throwable
     */
    public Object doSupport(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("doSupport");
        try {
            return process(joinPoint);
        } catch (Throwable t) {
            throw t;
        }
    }

    /**
     * 处理过程
     * @param joinPoint AOP切入点
     * @return
     * @throws Throwable
     */
    private Object process(ProceedingJoinPoint joinPoint) throws Throwable {
	System.out.println("process");
        Class<?> clazz = joinPoint.getTarget().getClass();
        String className = clazz.getSimpleName();//获取类名

        Signature signature = joinPoint.getSignature();
        Method method = ((MethodSignature) signature).getMethod();
        String methodName = method.getName();//获取方法名

        Method realMethod = clazz.getMethod(methodName, method.getParameterTypes());
	if (realMethod.isAnnotationPresent(Ann.class)) {
		... ...

		Ann ann = realMethod.getAnnotation(Ann.class);//获取注解
		System.out.println("ann:" + ann.value());
        }	
        return joinPoint.proceed();//执行方法
    }
 }
 spring配置

    <bean id="annoSupport" class="com.test.AnnoSupport"/>

    <bean id="TestAnn" class="com.test.TestAnn">
    </bean>
    <!-   注册注解处理器 -->
    <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>
测试类
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");
    }
    
}

猜你喜欢

转载自crabdave.iteye.com/blog/2373184