AOP通知描述了抽取的共性功能,根据共性功能,抽取的位置不同,最终运行代码时,要将其1添加到合理的位置
AOP通知分为五种类型
1.前置通知
before
2.后置通知
after
3.环绕通知(重点,有标准写法1)(权限校验之类的信息)
around
4.返回后通知(了解)
afterReturn
5.抛出异常后通知(了解)
afterThrowing
由于Around能模拟出其余四个的结构,所有我们把around当作本次的重点
AOP通知类型的案例
MyAdvise通知类:
package com.itheima.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component //让1配置类知道是bean
@Aspect //让配置类知道是造Aop,去识别一下的内容
public class MyAdvise {
@Pointcut("execution(void com.itheima.dao.BookDao.update())")
private void a(){}
@Pointcut("execution(int com.itheima.dao.BookDao.select())")
private void b(){}
//@Before("a()")
public void before(){
System.out.println("通知类中的before被触发");
}
//@After("a()")
public void after(){
System.out.println("通知类中的after被触发");
}
//@Around("a()")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("通知类中的around.before被触发");
//必须有一句话表述对原始操作的调用,因为无法预期调用的原始操作有没有异常,所以在这里卖弄,要先抛出最高异常
Object proceed = proceedingJoinPoint.proceed();
System.out.println("通知类中的around.after被触发");
return proceed;
}
//@Around("b()")
public Object aroundSelect(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("通知类中的around.before被触发");
//必须有一句话表述对原始操作的调用,因为无法预期调用的原始操作有没有异常,所以在这里卖弄,要先抛出最高异常
Object proceed = proceedingJoinPoint.proceed();
System.out.println("通知类中的around.after被触发");
return proceed;//返回值可以被更改,此时的返回为原始返回值
}
@AfterReturning("b()") //与After区别在于AfterReturning表示的是在最后
public void afterReturning() throws Throwable {
System.out.println("通知类中的afterReturning被触发");
}
@AfterThrowing("b()")//只有抛异常的时候才触发此通知
public void afterThrowing(){
System.out.println("通知类中的afterThrowing被触发");
}
}
SpringConfig Spring核心配置文件Java类
package com.itheima.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration //说明此文件为Spring配置类
@ComponentScan("com.itheima") //包扫描,加载bean
@EnableAspectJAutoProxy //启动了MyAdvise内的Aspect注解,
public class SpringConfig {
}
BookDaoImpl实现类,
package com.itheima.dao.impl;
import com.itheima.dao.BookDao;
import org.springframework.stereotype.Repository;
@Repository
public class BookDaoImpl implements BookDao {
@Override
public void update() {
System.out.println("update is running.......");
}
@Override
public int select() {
System.out.println("select is running.......");
int i = 1/0;
return 100;
}
}
app(mian方法)
package com.itheima;
import com.itheima.config.SpringConfig;
import com.itheima.dao.BookDao;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class App {
public static void main(String[] args) {
//获取Java配置类
AnnotationConfigApplicationContext acct = new AnnotationConfigApplicationContext(SpringConfig.class);
//获取bean
BookDao bean = acct.getBean(BookDao.class);
int select = bean.select();
System.out.println(select);
}
}