Spring——AOP总结

1 篇文章 0 订阅
1 篇文章 0 订阅

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();
	}

}

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值