Spring AOP

Spring AOP

AOP概念

AOP(Aspect Oriented Programming)为面向切面编程,实现业务逻辑与其他功能的分离。你可以决定在每个切面前或后添加其他功能(其他功能有日志,权限,事务等功能)使编写业务逻辑的人员只用专注于业务编程。

avatar

切面编程的术语

  1. ASpect(切面),切面通常指被封装需要插入的系统功能(日志等)
    ,就是在业务逻辑之间添加的其他功能,拥有其他功能的类需要加载到Spring容器中。
  2. Jionpoint(连接点)就是Spring允许你通知的地方,连接点的具体实现就是切入点。
  3. Pointcut(切入点),就是上面那幅图中的切点,切点能定位到的是任意一个业务逻辑类的任意函数。你可以通过切点的位置来插入你的切面,实现你需要的功能,最后会有一个实例。
  4. Advise(通知/增强处理),定义在切点位置上所执行的代码,也就是切面中类方法的实现。
  5. Target Object(目标对象),对应的是业务逻辑类中的某一方法,也就是切点所定位到的函数。
  6. Weave(织入),将切面插入到目标对象中,从而形成代理对象。
  7. 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()前后加入我们的权限处理过程,这里写的很简陋,就只是一个输出。

在这里插入图片描述

最终在业务逻辑前后就能插入我们的权限检查功能了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值