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的属性,遍历集合属性的值相关文章推荐
- C语言实现修改文本文件中特定行的实现代码(百度一天没找到,bing搜索十分钟就找到了)
- WebSocket不同版本的三种握手方式以及一个Netty实现JAVA类
- php字符串操作
- 刚开博客,水的开始!
- java笔记→递归算法、枚举法、辗转相除法
- python 图片格式转换产生的锯齿问题
- 一些统计特征与统计图的绘制-matlab
- JDK,cglib动态代理-AOP学习
- python入门,自制小爬虫获得百度贴吧内容
- C++中的explicit关键字
- java 反射详解
- git fork代码后保持更新同步
- java nio io模型
- 标题华为2016校招机试题(2015年9月) 海大上午场(包含实现代码,运行环境为vc)
- Python为什么这么火?
- JAVA - 优雅的记录日志(log4j实战篇)
- 向JAVA项目中导入jar包,需要进行设置。(安卓项目可直接导入)
- [Java基础] Java四类八种基本类型
- 3Sum leetcode第15题 Java代码
- RxJava----操作符:辅助操作符