SpringAop_切入点表达式 例子 原理
2015-11-04 23:09
411 查看
(..) 所有的方法 任意的参数, com.spring..* 子包
例子:
前提 需要导入包:
commons-logging.jar
spring.jar
cglib-nodep-2.1_3.jar
aspectjrt.jar
aspectjweaver.jar
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"> <!-- 加入aop的命名空间 xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation= http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd --> <bean id="personDao" class="com.spring.aop.xml.PersonDaoImpl"></bean> <bean id="transaction" class="com.spring.aop.xml.Transaction"></bean> <aop:config> <!-- 切入点表达式 :确定目标类 --> <aop:pointcut expression="execution(* com.spring.aop.xml.PersonDaoImpl.*(..) )" id="perform"/> <!-- ref 指向切面 --> <aop:aspect ref="transaction"> <aop:before method="beginTransaction" pointcut-ref="perform"/> <aop:after method="commit" pointcut-ref="perform" /> </aop:aspect> </aop:config> </beans>
切面
package com.spring.aop.xml; /** * 切面 */ public class Transaction { //通知 public void beginTransaction(){ System.out.println("beginTransaction "); } public void commit(){ System.out.println("commit transaction "); } }
目标类
package com.spring.aop.xml; public interface PersonDao { public void savePerson(); }
package com.spring.aop.xml; public class PersonDaoImpl implements PersonDao { @Override public void savePerson() { System.out.println("save person !"); } }
测试
package com.spring.aop.xml; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TransactionTest { @Test public void testTransaction(){ ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); PersonDao personDao = (PersonDao) context.getBean("personDao"); personDao.savePerson(); } }
输出:
beginTransaction
save person !
commit transaction
原理:
* 原理:
1.当Spring容器启动的时候,加载两个bean,对两个bean进行实列化
2.当Spring容器对应的配置文件解析到<aop:config>的时候
3.把切入点表达式解析出来,按照切入点表达式匹配spring容器内容的bean
4.如果匹配成功,则为该bean创建代理对象
5.当客户端利用context.getBean获取一个对象时,如果该对应有代理对象,则返回代理对象
如果没有代理对象,则返回对象本身
相关文章推荐
- java.sql.BatchUpdateException:
- Retrofit 入门--part2
- for遍历集合(jdk1.5推出来之后用最新的版本
- Java方法的重载和类的继承
- struts2表单重复提交
- Java 日志管理最佳实践
- MyEclipse6.5中SVN插件安装
- eclipse一直卡住,出现 “android sdk content loader 0%” 卡住的错误分析及解决方法
- SpringIoC依赖注入的过程(三)
- 【JDK源码】JDK/ArrayList源码逐行详解
- Java API 快速速查宝典
- Java实现通过递归遍历树形结构
- Eclipse搭建scala环境(解决“JDT weaving is currently disabled”问题)
- Java Log4j日志使用
- Java面向对象编程-第5章思考题
- Java中finalize()用法
- java 实现反转链表
- java的类学习
- struts2 ognl表达式
- Java 设计模式 概要