Spring-AOP操作(基于XML配置文件)
Spring-AOP操作(基于XML配置文件)
1.创建两个类,增强类和被增强类,创建方法
package com.orzjiangxiaoyu.aop.test3; /** * @author orz * @create 2020-08-17 21:31 */ public class Book { public void buy() { System.out.println("buy...."); } }
package com.orzjiangxiaoyu.aop.test3; /** * @author orz * @create 2020-08-17 21:32 */ public class BookProxy { public void before() { System.out.println("before..."); } }
2.在spring配置文件中创建两个类对象
3.在spring配置文件中配置切入点
<?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:p="http://www.springframework.org/schema/p" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 创建两个对像--> <bean id="book" class="com.orzjiangxiaoyu.aop.test3.Book"></bean> <bean id="bookproxy" class="com.orzjiangxiaoyu.aop.test3.BookProxy"></bean> <!-- 配置aop增强--> <aop:config > <!-- 切入点--> <aop:pointcut id="p" expression="execution(* com.orzjiangxiaoyu.aop.test3.Book.buy(..))"/> <!-- 配置切面--> <aop:aspect ref="bookproxy"> <!-- 增强作用在具体的方法上--> <aop:before method="before" pointcut-ref="p"></aop:before> </aop:aspect> </aop:config> </beans>
4.测试
package com.orzjiangxiaoyu.aop.test3; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author orz * @create 2020-08-17 21:38 */ public class Test1 { @Test public void test1() { ApplicationContext context=new ClassPathXmlApplicationContext("bean3.xml"); Book book = context.getBean("book", Book.class); book.buy(); } }
5.结果
before...
buy....