Spring AOP学习与简单例子

springAOP 封装了JDK和cglib
AOP分两类 :

1.以方法的参数进行拦截

2.对方法拦截
springAOP 属于方法级的

springAOP 实现方式
1.基于@AspectJ注解方式
2.基于xml配置的方式

基于注解实现:

定义核心业务逻辑接口

public interface eatMan {
void eat();
}

定义核心业务逻辑接口实现

@Service
//@Component
public class human implements eatMan {
@Override
public void eat() {
// int b=0;
// int a=2/b;
System.out.println("吃。。。。。。。。。。。。");
}

@Override
public String haha() {
return "赵";
}
}

自定义springAop注解

//注入到容器中
@Component
//切面注解
@Aspect
public class notify {
public notify() {

}

//写了一个通用的拦截切面 ,拦截的是eat()方法

@Pointcut("execution(* *.eat(..))")
public void eatNotify() {
}

切面(eatNotify()方法)之前执行:

@Before("eatNotify()")
public void before(){
System.out.println("before....");
}

切面(eatNotify()方法)之后执行:

@After("eatNotify()")
public void after(){
System.out.println("after....");
}

切面执行出错就会执行这个方法:

@AfterThrowing(value = "eatNotify()",throwing = "e")
public void exception(Throwable e){
System.out.println("eat()方法异常信息为"+e);
}

方法的返回值:

@Override
public String haha() {
return "赵";
}
下面返回的是“赵”
@AfterReturning(value ="execution(* *.haha(..))",returning = "re")
public void returns(String re) throws Throwable {
System.out.println("名字:"+re);
}

// 定义环绕通知方法
// 方法必须接受 ProceedingJoinPoint 为参数,因为要通过它来调用被通知的方法。
// 我们可以在方法中执行其他操作。当需要执行被通知的方法时
// 就调用 ProceedingJoinPoint 的 proceed()。

// @Around("eatNotify()")
// public void aroud(ProceedingJoinPoint p) {
// {
// System.out.println("before...."); // 相当于@Before
//
// try {
// p.proceed();// 通过调用此方法来执行被通知的方法
// System.out.println("after......"); // 相当于@After
// } catch (Throwable throwable) {
// throwable.printStackTrace();//相当于@AfterThrowing
// }
// }
// }
}

配置aop扫描,基于注解,也可以用xml的形式

@Configuration
@EnableAspectJAutoProxy
@ComponentScan("com.lala.zhao.aop.test")
public class config {
}

测试:

//@ContextConfiguration(classes = config.class)
public class testMain {
private static ApplicationContext ctx;
// @Autowired
// eatMan eat;
@Test
public void mai (){
ctx=new AnnotationConfigApplicationContext(config.class);
eatMan eat= (eatMan) ctx.getBean(eatMan.class);

eat.eat();
eat.haha();
}
}

posted @ 2020-03-27 17:46  Angry-rookie  阅读(267)  评论(0)    收藏  举报