位址連結:
使用完全注解開發實作AOP
上一篇寫了如何使用注解實作Aop切面程式設計、這一篇使用xml方式實作aop切面程式設計。通過對比、可以有效看出兩者之間的友善程度
1、建立兩個類,增強類和被增強類,建立方法
1.1 被增強類Dog.java
對這個類裡的方法進行增強
/**
* @author Lenovo
* @version 1.0
* @data 2022/10/23 14:58
*/
public class Dog {
public void show(){
System.out.println("我是小狗旺财。。。。");
}
}
1.2 增強類DogProxy.java
/**
* @author Lenovo
* @version 1.0
* @data 2022/10/23 14:59
*/
public class DogProxy {
public void before(){
System.out.println("我是提前執行的、我是一隻黑色的小狗。。。。");
}
}
2、在 spring 配置檔案中建立兩個類對象
<!--建立對象-->
<bean id="dog" class="com.zyz.spring5.aopxml.Dog"></bean>
<bean id="dogProxy" class="com.zyz.spring5.aopxml.DogProxy"></bean>
3、在 spring 配置檔案中配置切入點
有關切入點、切面等術語的講解。上一篇有專門的講解。這裡不在贅述。開頭的連結
<!--配置增強-->
<aop:config >
<!--切入點-->
<aop:pointcut id="p" expression="execution(* com.zyz.spring5.aopxml.Dog.show(..))"/>
<!--配置切面-->
<aop:aspect ref="dogProxy">
<!--增強作用在具體的方法上-->
<aop:before method="before" pointcut-ref="p"></aop:before>
</aop:aspect>
</aop:config>
4、測試
@org.junit.Test
public void testDemo2(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
Dog dog = context.getBean("dog", Dog.class);
dog.show();
}
5、測試結果

6、後語
<?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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--建立對象-->
<bean id="dog" class="com.zyz.spring5.aopxml.Dog"></bean>
<bean id="dogProxy" class="com.zyz.spring5.aopxml.DogProxy"></bean>
<!--配置增強-->
<aop:config >
<!--切入點-->
<aop:pointcut id="p" expression="execution(* com.zyz.spring5.aopxml.Dog.show(..))"/>
<!--配置切面-->
<aop:aspect ref="dogProxy">
<!--增強作用在具體的方法上-->
<aop:before method="before" pointcut-ref="p"></aop:before>
</aop:aspect>
</aop:config>
</beans>