需求類:
PersonDao類:接口
PersonDaoImpl類:實現類
Transaction類:事務類
TransactionTest類:測試類
applicationContext.xml:配置文件
PersonDao:
package com.tgb.spring.aop.xml.transaction;
public interface PersonDao {
public void savePerson();
}
PersonDaoImpl:
package com.tgb.spring.aop.xml.transaction;
public class PersonDaoImpl implements PersonDao {
public void savePerson() {
System.out.println("執行: save person 方法!");
}
}
Transaction:
package com.tgb.spring.aop.xml.transaction;
import java.lang.reflect.Method;
import org.junit.Test;
/**
*
* @author F-mdh
*
*/
//切面
public class Transaction {
public void beginTransaction(){
System.out.println("執行:開啓事務!");
};
public void commitTransaction(){
System.out.println("執行:提交事務!");
};
}
TransactionTest:
package com.tgb.spring.aop.xml.transaction;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TransactionTest {
@Test
public void testTransaction(){ //applicationContext.xml
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
PersonDao personDao=(PersonDao)context.getBean("personDao");
personDao.savePerson();
};
}
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.tgb.spring.aop.xml.transaction.PersonDaoImpl"></bean>
<bean id="transaction" class="com.tgb.spring.aop.xml.transaction.Transaction"></bean>
<aop:config>
<!--
切入點表達式 確定目標類
-->
<aop:pointcut
expression="execution(* com.tgb.spring.aop.xml.transaction.PersonDaoImpl.*(..))"
id="perform"/>
<!--
ref指向的對象就是切面
-->
<aop:aspect ref="transaction">
<aop:before method="beginTransaction" pointcut-ref="perform"/>
<aop:after-returning method="commitTransaction" pointcut-ref="perform"/>
</aop:aspect>
</aop:config>
</beans>