您的位置:首页 > 编程语言

AOP面向切面编程

2016-05-03 20:08 302 查看

aop概念

aop:
1、切面
事务、日志、安全性框架、权限等都是切面
2、通知
切面中的方法就是通知
3、目标类
4、切入点
只有符合切入点,才能让通知和目标方法结合在一起
5、织入:
形成代理对象的方法的过程

好处:
事务、日志、安全性框架、权限、目标方法之间完全是松耦合的

Spring AOP例子

一个方法的完整表示 修饰 返回值类名 方法名(参数类型) 抛出的异常类型切入点表达式execution(public * *(..)) 所有的公共方法 execution(* set*(..)) 以set开头的任意方法 execution(* com.xyz.service.AccountService.*(..)) com.xyz.service.AccountService类中的所有的方法 execution(* com.xyz.service.*.*(..)) com.xyz.service包中的所有的类的所有的方法 execution(* com.xyz.service..*.*(..)) com.xyz.service包及子包中所有的类的所有的方法 execution(* cn.itcast.spring.sh..*.*(String,?,Integer)) cn.itcast.spring.sh包及子包中所有的类的有三个参数 第一个参数为String,第二个参数为任意类型, 第三个参数为Integer类型的方法 例子:spring配置文件applicationContext.xml<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <!-- 导入目标类,导入切面--> <bean id="personDao" class="springAOP.cn.itcast.aop.PersonDaoImpl"></bean> <bean id="myTransaction" class="springAOP.cn.itcast.aop.MyTransaction"></bean> <!-- aop配置 --> <aop:config> <!-- 切入点表达式=目标方法 --> <aop:pointcut expression="execution(* springAOP.cn.itcast.aop.PersonDaoImpl.*(..) )" id="perform"/> <!-- 切面 --> <aop:aspect ref="myTransaction"> <aop:before method="beginTran" pointcut-ref="perform"/> <aop:after-returning method="commit" pointcut-ref="perform" /> </aop:aspect> </aop:config> </beans> 测试public void test1(){ApplicationContext context = new ClassPathXmlApplicationContext("/springAOP/cn/itcast/aop/applicationContext.xml");PersonDao personDao = (PersonDao) context.getBean("personDao");Person person = new Person();person.setPname("wang");person.setPsex("male");System.out.println(personDao);personDao.savePerson(person);}}

AOP代理原理

springAOP的具体加载步骤: 1、当spring容器启动的时候,加载了spring的配置文件 2、为配置文件中所有的bean创建对象 3、spring容器会解析aop:config的配置 1、解析切入点表达式,用切入点表达式和纳入spring容器中的bean做匹配 如果匹配成功,则会为该bean创建代理对象,代理对象的方法=目标方法+通知 如果匹配不成功,不会创建代理对象 4、在客户端利用context.getBean获取对象时,如果该对象有代理对象则返回代理对象,如果代理对象,则返回目标对象 说明:如果目标类没有实现接口,则spring容器会采用cglib的方式产生代理对象,如果实现了接口,会采用jdk的方式 <s:debug></s:debug>是深度变量的,遍历一个bean的属性,遍历集合属性的值


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: