什么是前置通知,就是当执行某一个方法的时候,会自动执行另一个方法
第一步
引入架包
第二部
创建一个简单的类,实现一个接口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();
}
}