同样是拿一个Person类和Transaction类来举例子

 

导入相关的jar包



Person.java

public interface PersonDao {
public void savePerson();
}

public class PersonDaoImpl implements PersonDao {
public void savePerson() {
System.out.println("savePerson");
}
}


Transaction.java

public class Transaction {
public void beginTransaction(){
System.out.println("beginTransaction");
}
public void commit(){
System.out.println("commit");
}
}




在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="com.mo.transaction.PersonDaoImpl"></bean>
<bean id="transaction" class="com.mo.transaction.Transaction"></bean>

<aop:config>
<!-- 切入点表达式,确定目标类 -->
<aop:pointcut
expression="execution(* com.mo.transaction.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>



测试单元


@Test
public void aopTest(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
PersonDao personDao = (PersonDao)context.getBean("personDao");
personDao.savePerson();
}

测试的结果


beginTransaction

savePerson

commit