上次我已经写过aop用注解实现的这次是用配置实现,个人感觉配置实现比较好,毕竟程序是给人看的吗,配置里写的一清二楚,别人看来也好懂,而且配置修改起来也比较容易,便于后期维护及修改,而才用注解方式的修改,需要修改注解,或者重写实现类,比较麻烦,建议采用配置方式实现,至于性能方面,目前处于学习阶段,没有感受出来
代码样例:
自定义的切面代码
package com.leige.aop;
public class MyInterceptor {
public void before(){
System.out.println("前置通知");
}
public void doAfterReturning(){
System.out.println("后置通知");
}
public void doAfter(){
System.out.println("最终通知");
}
public void doAfterThrowing(){
System.out.println("异常通知");
}
}
配置详解
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!-- <aop:aspectj-autoproxy/>
<context:annotation-config/>
<context:component-scan base-package="com.leige"/>-->
<bean id="personDao" class="com.leige.daoimpl.PersonDaoImpl"></bean>
<bean id="personService" class="com.leige.service.PersonService" >
<property name="dao" ref="personDao"></property>
</bean>
<bean id="aop" class="com.leige.aop.MyInterceptor"></bean>
<aop:config>
<aop:aspect id="aop1" ref="aop">
<aop:pointcut id="cut" expression="execution (* com.leige.daoimpl.PersonDaoImpl.*(..))" />
<aop:before pointcut-ref="cut" method="before"/>
<aop:after-returning pointcut-ref="cut" method="doAfterReturning"/>
</aop:aspect>
</aop:config>
</beans>
实现代码
package com.leige.junit;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.leige.service.PersonService;
public class PersonTest {
ApplicationContext app=new ClassPathXmlApplicationContext("beans.xml");
@Test
public void fun(){
PersonService service=(PersonService)app.getBean("personService");
service.getDao().add();
}
}
结果