基于配置文件的AOP操作
1.创建两个类 增强类 和被增强类 创建方法
2.在spring中的配置文件中 创建两个对象
3.配置切入点
开发测试
实体类
public class Book {
public void buy(){
System.out.println("买书");
}
}
代理对象
package com.hui;
public class BookProxy {
public void buyBefore(){
System.out.println("before...");
}
}
beans.xml
<?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="book" class="com.hui.Book"></bean>
<bean id="bookProxy" class="com.hui.BookProxy"></bean>
<!-- 配置切入点 实现增强-->
<aop:config>
<!-- 切入点-->
<aop:pointcut id="pointCut" expression="execution(* com.hui.Book.buy(..))"/>
<!-- 切面 bookProxy是切面-->
<aop:aspect ref="bookProxy">
<!-- 解释: bookProxy上的byBefore方法作用在了 buy方法上面 前置 -->
<!-- 配置增强到具体的方法上-->
<!-- 把buyBefore方法 加到pointCut这个切入点上 前置通知-->
<aop:before method="buyBefore" pointcut-ref="pointCut"></aop:before>
</aop:aspect>
</aop:config>
测试:
@org.junit.Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Book book = context.getBean("book", Book.class);
book.buy();
}