springAOP的第一个例子

来源:互联网 发布:一叶子面膜怎么样知乎 编辑:程序博客网 时间:2024/06/08 08:34

同样是拿一个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>


测试单元

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


测试的结果

beginTransaction

savePerson

commit


0 0
原创粉丝点击