Spring AOP
AOP概念
AOP(Aspect Oriented Programming)为面向切面编程,实现业务逻辑与其他功能的分离。你可以决定在每个切面前或后添加其他功能(其他功能有日志,权限,事务等功能)使编写业务逻辑的人员只用专注于业务编程。
切面编程的术语
- ASpect(切面),切面通常指被封装需要插入的系统功能(日志等)
,就是在业务逻辑之间添加的其他功能,拥有其他功能的类需要加载到Spring容器中。 - Jionpoint(连接点)就是Spring允许你通知的地方,连接点的具体实现就是切入点。
- Pointcut(切入点),就是上面那幅图中的切点,切点能定位到的是任意一个业务逻辑类的任意函数。你可以通过切点的位置来插入你的切面,实现你需要的功能,最后会有一个实例。
- Advise(通知/增强处理),定义在切点位置上所执行的代码,也就是切面中类方法的实现。
- Target Object(目标对象),对应的是业务逻辑类中的某一方法,也就是切点所定位到的函数。
- Weave(织入),将切面插入到目标对象中,从而形成代理对象。
- Proxy(代理),spring能够动态的生成代理对象。
例子
业务类 添加金钱
切面 模拟权限检查
1.demo1.java(主函数)
package club.yzreb.AOP.blog;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class demo1 {
public static void main(String args[]) {
ApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "applicationContext.xml" });
Business business=(Business)context.getBean("business");
business.addMoney();
}
}
2.myAspect.java(切面)
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
//使用@Aspect 给这个类定义为 切面
@Aspect
@Component
public class myAspect {
//环绕通知 value = "用来申明 切点 所指向的位置"
@Around(value="execution(* club.yzreb.AOP.blog.Business.*(..))")
public void myBefore(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("模拟执行权限检查\n");
joinPoint.proceed();//执行切点 所指向的函数
System.out.println("添加完成\n");
}
}
3.Business.java(业务类)
package club.yzreb.AOP.blog;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
//定义一个业务类
@Component("business")
public class Business {
//定义一个业务方法 addMoney()添加金钱
public void addMoney() {
System.out.println("成功添加100万\n");
}
}
4.别忘在applicationContext.xml添加
<aop:aspectj-autoproxy/> //告诉spring 用注解方式写AOP
5.运行结果
就是在业务类Business.addMoney()前后加入我们的权限处理过程,这里写的很简陋,就只是一个输出。
最终在业务逻辑前后就能插入我们的权限检查功能了