Spring AOP前置通知

本文介绍了Spring AOP中的前置通知概念,即在执行特定方法前自动调用另一方法。通过三步实现:引入AOP相关库,创建并实现MethodBeforeAdvice接口以定义before方法作为前置通知,最后在XML配置文件中设置切入点和通知关联,确保在指定方法执行时触发前置通知。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是前置通知,就是当执行某一个方法的时候,会自动执行另一个方法

第一步

引入架包

第二部

创建一个简单的类,实现一个接口MethodBeforeAdvice

重写bofore方法(前置)
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
    System.out.println("前置通知");    
}
使得这个类具有通知的功能

导入源码

 

 

 

第三步

让方法与通知相关联

在bean中添加aop

   找到类中的方法,要写全类名,用execution(),起一个名字poiontcut

   将他与前置通知相关联

<!-- 将方法所在类与通知关联 -->
    <aop:config>
        <aop:pointcut expression="execution(public void service.studentService.addstudent())" id="poiontcut"/><!-- 切入点,在哪               里执行通知 -->
        <!--advisor:相当于连接切入点和切面的线  -->
        <aop:advisor advice-ref="aop" pointcut-ref="poiontcut"/>
    </aop:config>

<!-- 配置前置通知 -->
    <!-- 即将调用方法所在的类 -->
    <bean id="studnetservice" class="service.studentService">
    </bean>
    
    <!-- 前置通知所在的类 -->
    <bean id="aop" class="all.aop"></bean>
    
    <!-- 将方法所在类与通知关联 -->
    <aop:config>
        <aop:pointcut expression="execution(public void service.studentService.addstudent())" id="poiontcut"/><!-- 切入点,在哪里执行通知 -->
        <!--advisor:相当于连接切入点和切面的线  -->
        <aop:advisor advice-ref="aop" pointcut-ref="poiontcut"/>
    </aop:config>

前置通知

package all;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

public class aop implements MethodBeforeAdvice {

	@Override
	public void before(Method method, Object[] args, Object target) throws Throwable {
		// TODO Auto-generated method stub
		System.out.println("前置通知");
	}

}

 前置通知相对应的类的方法

package service;
public class studentService {
     public  void  addstudent() {
    	 System.out.println("在此之前还有前置通知");
     }    
}

测试类

package school;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import all.allCollectionType;
import service.studentService;
public class Test {
     public static void main(String[] args) {
    	
    	 studentservice() ;
     }
     public static void studentservice() 
     {
    	 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    	 studentService stdts = (studentService)context.getBean("studnetservice");
    	 stdts.addstudent();
     }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值