spring aop切面動態代理xml配置實現
上次我已經寫過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();
}
}
結果