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

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获取一个对象时,如果该对应有代理对象,则返回代理对象
如果没有代理对象,则返回对象本身
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: