此文章演示为纯配置文件形式,如需注解形式请参考文章
1:引入AOP依赖
<!--Spring AOP-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
2:创建一个java代理类
public class LogCut {
public void before() {
System.out.println("前置通知1.....");
}
}
3:创建一个被代理的java类
public class People implements Serializable {
public People() {
}
public void init(){
System.out.println("初始化方法");
}
}
4:修改Spring配置文件
4.1:添加命名空间
4.2: 添加配置文件
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<bean class="org.example.IOC.entiy.People" id="people01"></bean>
<!-- 注册对象-->
<bean id="people" class="org.example.IOC.entiy.People"></bean>
<bean id="logCut" class="org.example.AOP.aspect.LogCut"></bean>
<!-- 开启AOP代理-->
<aop:aspectj-autoproxy/>
<!--aop相关配置-->
<aop:config>
<!--aop切面 ref引入AOP对象,就是上面的ID-->
<aop:aspect ref="logCut">
<!-- 定义aop 切入点 expression就是Pointcut语法,这里表示代理 org.example 包及子包下所有方法-->
<aop:pointcut id="cut" expression="execution(* org.example..*.*(..))"/>
<!-- 配置前置通知 指定前置通知方法名 并引用切入点定义 -->
<aop:before method="before" pointcut-ref="cut"/>
<!-- <!– 配置返回通知 指定返回通知方法名 并引用切入点定义 –>-->
<!-- <aop:after-returning method="afterReturn" pointcut-ref="cut"/>-->
<!-- <!– 配置异常通知 指定异常通知方法名 并引用切入点定义 –>-->
<!-- <aop:after-throwing method="afterThrow" throwing="e" pointcut-ref="cut"/>-->
<!-- <!– 配置最终通知 指定最终通知方法名 并引用切入点定义 –>-->
<!-- <aop:after method="after" pointcut-ref="cut"/>-->
<!-- <!– 配置环绕通知 指定环绕通知方法名 并引用切入点定义 –>-->
<!-- <aop:around method="around" pointcut-ref="cut"/>-->
</aop:aspect>
</aop:config>
</beans>
5:代码测试
@Test
public void test07(){
ClassPathXmlApplicationContext app=new ClassPathXmlApplicationContext("Spring003_AOP.xml");
People people01 = app.getBean("people", People.class);
people01.init();
}