zoukankan      html  css  js  c++  java
  • Spring AOP

    什么是AOP(Aspect Oriented Programming):

      我们一直把OOP(Object Oriented Programming)面向对象的编程称之为纵向编程方式,它以一条线的方式向终点延伸,可以想象成一条条绵延无尽的道路。而往往会出现一种情况:许多不同的路会交织在一起,这就是所谓的不同的对象之间会有存在相同的处理逻辑。为了使这部分逻辑能够得到重用,更好的理解,更方便的维护,就出现了AOP(Aspect Oriented Programming)面向方面的编程思想,称之为横向编程方式。

    怎么实现AOP:

      AOP编程思想是通过代理技术来实现的,这个可以参考设计模式,然后研究一下java动态代理技术来了解。

      在Spring中有两种方式实现代理:

        1.JDK动态代理:其代理对象必须是某个接口的实现,它是通过在运行期间创建一个接口的实现类来完成对目标对象的代理的。

        2.CHLIB代理:实现原理类似于JDK动态代理,只是它在运行期间生成的代理对象是针对目标类扩展的子类,DGLIB是高效的代码生成包,底层是依赖ASM操作字节码实现的,性能比JDK强。但是对于类中final的方法和类无法代理。(需要将CGLIB二进制发行包放到classpath下面)。

    下面我们将实现一个简单的例子:

    //java代码
    @Aspect
    public class AspectJTest {
    	
    	@Pointcut("execution(* *.test(..))")
    	public void test(){
    		System.out.println("test");
    	}
    	
    	@Before("test()")
    	public void beforeTest(){
    		System.out.println("before");
    	}
    	
    	@After("test()")
    	public void afterTest(){
    		System.out.println("111");
    		object=null;
    		try {
    			o = p.proceed();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		
    		System.out.println("2222");
    	}
    	
    	@Around("test()")
    	public void aroundTest(ProceedingJoinPoint p){
    		System.out.println("");
    	}
    
    }

    //配置文件

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/beans/spring-aop-3.0.xsd">
    <!-- 启动对@AspectJ注解的支持 -->
    <aop:aspectj-autoproxy/>
    </beans>

    实现AOP的代理的代理原则:

      如果目标对象实现了接口,默认情况下采用JDK的动态代理实现AOP。

      如果目标对象实现了接口,可以强制其使用CGLIB实现AOP可是在配置文件中加入<aop:aspectj-autoproxy proxy-target-class="true">。

      如果慕白哦对象没有实现接口,必须采用CGLIB库,Spring会自动在JDK代理和CGLIB之间转换。  

  • 相关阅读:
    hdu 5224 Tom and paper 水题
    2015 UESTC 搜索专题N题 韩爷的梦 hash
    2015 UESTC 搜索专题M题 Palindromic String 马拉车算法
    2015 UESTC 搜索专题K题 秋实大哥の恋爱物语 kmp
    2015 UESTC 搜索专题J题 全都是秋实大哥 kmp
    2015 UESTC 搜索专题F题 Eight Puzzle 爆搜
    2015 UESTC 搜索专题E题 吴队长征婚 爆搜
    2015 UESTC 搜索专题D题 基爷的中位数 二分
    2015 UESTC 搜索专题C题 基爷与加法等式 爆搜DFS
    2015 UESTC 搜索专题B题 邱老师降临小行星 记忆化搜索
  • 原文地址:https://www.cnblogs.com/lvxiaowei/p/4229994.html
Copyright © 2011-2022 走看看