一、什么是AOP
AOP 的全称是 Aspect Orient Programming ,即面向切面编程。是对OOP( Object Orient Programming )的一种补充,专门用于处理一些具有横切性质的服务。常常用于日志输出、安全控制等。
二、Spring Aop的使用
1. 定义待切入方法(eating())
package com.simplenote.aop;
import org.springframework.stereotype.Component;
/**
* @author xxxx
*/
@Component
public class Person {
public void eating(){
System.out.println("吃饭!");
}
}
2. 定义切面(Aspect)
- 注:切面包含通知(Advice)和切入点(Pointcut)
package com.simplenote.aop;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* @author xxxx
*/
@Component
@Aspect
public class PersonAspect {
@Before("execution(* *..aop.Person.eating(..))")
public void before(){
System.out.println("饭前洗手!");
}
@AfterReturning("execution(* *..aop.Person.eating(..))")
public void afterReturning(){
System.out.println("饭后洗手!");
}
@AfterThrowing("execution(* *..aop.Person.eating(..))")
public void afterThrowing(){
System.out.println("吃饭时被鱼刺卡到喉咙!");
}
@After("execution(* *..aop.Person.eating(..))")
public void after(){
System.out.println("我刚刚吃饭了!");
}
}
3. 执行eating()
package com.simplenode.aop;
import com.simplenote.SimpleNoteApplication;
import com.simplenote.aop.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SimpleNoteApplication.class)
public class AopTest {
@Autowired
private Person person;
@Test
public void aopTest(){
person.eating();
}
}
- eating()正常执行
- eating()发生异常
4. 环绕通知(Around)
细心的小伙伴,应该已经发现上面的代码中并没有出现环绕通知,其实环绕通知是Spring Aop提供给开发都自行选择时机调用通知方法的一种方法。对上面的代码改造一下,即可使用环绕通知,运行结果与上面一致。
package com.simplenote.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* @author xxxx
*/
@Component
@Aspect
public class PersonAspect {
@Around("execution(* *..aop.Person.eating(..))")
public Object aroundPrintLog(ProceedingJoinPoint pjp){
Object reValue = null;
try {
Object[] args = pjp.getArgs();
before();
reValue = pjp.proceed(args);
after();
} catch (Throwable t){
afterThrowing();
} finally {
after();
}
return reValue;
}
private void before(){
System.out.println("饭前洗手!");
}
private void afterReturning(){
System.out.println("饭后洗手!");
}
private void afterThrowing(){
System.out.println("吃饭时被鱼刺卡到喉咙!");
}
private void after(){
System.out.println("我刚刚吃饭了!");
}
}
- eating()正常执行
- eating()发生异常
三、总结
- AOP是一种面向切面编程的思想,在处理一些专具有横切性质的服务时,使用AOP编程会大大提高开发的效率。
- Spring Aop则是Spring提供给开发者,让开发者只需关注开发通知/切面本身,而不用过多的关注通知方法织入(Weaving)过程的一种工具。