AOP的作用
通过AOP我们可以将那些与业务无关的,却为业务模块所共同公共调用的逻辑或者责任封装起来,进而便于减少系统的重复代码量,并且能够降低模块间的耦合度,并有利于未来的可操作性和可维护性,降低了维护成本。比如日志、事务管理、缓存等。
AOP的基本概念
1.Aspect(切面):通常是一个类,里面可以定义切入点和通知
2.JointPoint(连接点):程序执行过程中明确的点,一般是方法的调用
3.Advice(通知):AOP在特定的切入点上执行的增强处理,有before,after,afterReturning,afterThrowing,around
4.Pointcut(切入点):就是带有通知的连接点,在程序中主要体现为书写切入点表达式
5.AOP代理:AOP框架创建的对象,代理就是目标对象的加强。Spring中的AOP代理可以使JDK动态代理,也可以是CGLIB代理,前者基于接口,后者基于子类
AOP实现方式
1.经典的基于代理的AOP
2.@AspectJ注解驱动的切面
3.纯POJO切面
4.注入式AspectJ切面
感觉自己用的最多的就是第二种。写个案例,上课和下课是每个人相同的行为,而上课中的表现每个人是不同的。
package com.example.demo.AOPTest;
import org.springframework.stereotype.Component;
@Component
public class student implements AttendClass{
@Override
public void behavior() {
System.out.println("不同的人上课有不同的行为。。。");
}
}
package com.example.demo.AOPTest;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class studentAspect{
//execution切入点表达式:https://blog.csdn.net/u012887385/article/details/54600706
@Pointcut("execution(* com.example.demo..*(..))")
public void JointPoint(){}
@Before("JointPoint()")
public void classBegin(){
System.out.println("上课");
}
@After("JointPoint()")
public void classAfter(){
System.out.println("下课");
}
}
junit测试
package com.example.demo;
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;
import com.example.demo.AOPTest.student;
import com.example.demo.service.adminText;
import com.example.demo.service.currentUserHollder;
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Autowired
private student stu;
@Test
public void contextLoads() {
stu.behavior();
}
}