//目标对象接口
public interface PersonDao {
public String savePerson();
}
//目标对象俱体实现类
public class PersonDaoImpl implement PersonDao {
public String savePerson() {
System.out.println("save person");
return "aaaaa";
}
}
//事务处理类:切面
public class Transaction {
public void beginTransaction(){
System.out.println("开启事务");
}
public void commit(){
System.out.println("事务提交");
}
@Test
public void test(){
Class class1 = Object.class;
Method[] methods = class1.getMethods();
for(Method method:methods){
System.out.println(method.toString());
}
}
}
//客户端测试
@Test
public void testProxy(){
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
PersonDaoImpl personDao =
(PersonDaoImpl)context.getBean("personDao");
personDao.savePerson();
}
//spring.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="com.itheima09.spring.aop.xml.transaction.PersonDaoImpl">
</bean>
<bean id="transaction"
class="com.itheima09.spring.aop.xml.transaction.Transaction">
</bean>
<!--
aop:config的配置
-->
<aop:config>
<!--
expression :切入点表达式
id :为标示符,可以配置多个表达式
注意:表达式越精确,效率越高,表达式需要包含目标类,
才能使用代理对象
-->
<aop:pointcut
expression="execution(* com.itheima09.spring.aop.xml.transaction.PersonDaoImpl.*(..))"
id="perform"/>
<!--
ref指向切面
-->
<aop:aspect ref="transaction">
<!--
前置通知 在目标方法输出之前执行
method 前置通知的名字
pointcut-ref 指向切入点表达式
-->
<aop:before method="beginTransaction" pointcut-ref="perform"/>
<aop:after-returning method="commit" pointcut-ref="perform"/>
</aop:aspect>
</aop:config>
</beans>
aop执行原理
说明:
1、context.getBean时,如果该类没有生成代理对象,则返回对象本身
2、如果产生了代理对象,则返回代理对象
3、如果目标类实现了接口,则采用jdkproxy生成代理对象,如果目标类没有实现接口,则采用cglibproxy生成代理对象,而生成代理对象是由spring容器内部完成的。
切入点表达式