2014/3/27 Spring AOP编程心得

来源:互联网 发布:微信闪退修复软件 编辑:程序博客网 时间:2024/05/16 00:51

笔者今日对于Spring的核心思想之一的AOP(切面编程)进行了初步理解与接触,学的不太好,结合书本基本上还是理解实现了AOP编程,废话不多说,以下是Demo:

本人认为AOP就是一些类拥有的共同的功能代码,提取出来,像是用刀子横切了这些类一样,然后有切面,切面包含切点(cutPoint)和增强(Advice)

1.首先是Controller里的方法和工程路径


第二个红框表示我使用AOP的入口


IndexController.java中的aop方法

/**     *      * 测试aop切面编程配置文件: <br>     * 〈功能详细描述〉     *     * @return     * @see [相关类/方法](可选)     * @since [产品/模块版本](可选)     */    @ResponseBody    @RequestMapping("/aop.action")    @NeedTest(flag = true)    public Map<String, Object> aop(){        Map<String, Object> map = new HashMap<String, Object>();        map.put("name", "suning");        return map;    }
我定义了一个NeedTest标签,表示是否要测试,参数为true


2.对应此标签有一个接口

NeedTest.java

package com.suning.sample.interfaces;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;@Retention(value = RetentionPolicy.RUNTIME)   //运行时加载jvm,并支持反射查找注解public @interface NeedTest {    boolean flag();}
注意的是@interface是要求格式,该接口中定义的抽象方法必须无参


3:切面配置文件

application-aop.xml

<!-- 植入aop增强 --><aop:config proxy-target-class="true"><aop:aspect ref="needTest"><aop:pointcut expression="execution(* com.suning.sample.web.*.*(..))"id="needTestPointcut" /><aop:after-returning method="needTestMethod"pointcut-ref="needTestPointcut" returning="map"/></aop:aspect></aop:config><bean id="needTest" class="com.suning.sample.interfaces.NeedTestImp"></bean>

<aop:config proxy-target-class="true">
true表示我使用CGLib代理,false代表使用JDK代理,代理没有吃透,待学习


<aop:pointcut expression="execution(* com.suning.sample.web.*.*(..))"id="needTestPointcut" /><aop:after-returning method="needTestMethod"pointcut-ref="needTestPointcut" returning="map"/>
代表我扫描com.suning.sample.web下所有的类的所有的方法,只有当方法返回一个map对象,才会调用NeedTestImp.java类的needTestMethod方法,并把map对象传进去


4.相关的java类

NeedTestImp.java

package com.suning.sample.interfaces;import java.lang.reflect.Method;import java.util.Map;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.reflect.MethodSignature;import org.slf4j.Logger;import org.slf4j.LoggerFactory;public class NeedTestImp {        private static final Logger logger = LoggerFactory.getLogger(NeedTestImp.class);        public void needTestMethod(JoinPoint joinPoint, Map<String,Object> map){        System.out.println("根据flag判断是否允许测试");        //得到类路径        String classType = joinPoint.getTarget().getClass().getName();        logger.debug("类路径" + classType);        // 得到方法名        String methodName = joinPoint.getSignature().getName();        MethodSignature jp = (MethodSignature) joinPoint.getSignature();        Method method = jp.getMethod();        // 得到方法参数        Class<?>[] parameterTypes = method.getParameterTypes();        Class<?> className = null;    }}

这里主要是为了展示我传入的map对象以及IndexController.java中的aop方法有关参数

如下:



心得:AOP编程有点像黑客,给某些切入点追加代码,可以在方法前,后等。追加的代码是自己定义的。偷笑







0 0