AOP笔记
AOP
idea是使用AOP必须要引入的依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
什么是AOP
AOP (Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可看用性,同时提高了开发的效率

AOP在Spring中的作用
- 横切关注点:跨越应用程序的方法或者模块。即使,与我们业务逻辑无关,但是我们需要关注的部分就是横切关注点。日志、安全、缓存、业务、事务
- 切面(aspect):横切关注点被模块化的特殊对象。及他是一个类
- 通知(advice):切面必须完成的工作。类的一个方法
- 目标(target):被通知对象
- 代理(Proxy):向目标对象通知创建的对象
- 切入点(PointCut):切面通知执行的地点的定义
- 连接点(JoinPonint):与切入点匹配的执行点(可以获取切点执行的方法一般用来打印日志)
三种方式
- 一种原生Spring的API接口
UserService
public interface UserService {
void add();
void del();
void select();
void update();
}
UserServiceImpl
public class UserServiceImpl implements UserService {
@Override
public void add() {
System.out.println("添加的方法");
}
@Override
public void del() {
System.out.println("删除的方法");
}
@Override
public void select() {
System.out.println("查询的方法");
}
@Override
public void update() {
System.out.println("修改的方法");
}
代理类Aspect
public class Aspect implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println("代理方法");
}
}
XML配置
<!--方式一使用原生的API-->
<aop:config proxy-target-class="true" >
<aop:pointcut id="point" expression="execution(* Demo1.service.impl.UserServiceImpl.*(..))"/>
<!--环绕通知-->
<aop:advisor advice-ref="aspect" pointcut-ref="point"/>
</aop:config>
- 自定义实现
代码练习
public class Log {
public void berore(){
System.out.println("====================方法执行前===========================");
}
public void after(){
System.out.println("======================方法执行后==========================");
}
}
配置
<!--开启Aop-->
<aop:config proxy-target-class="true">
<!--自定义切面 ref要引用的bean-->
<aop:aspect ref="log">
<!--切点 -->
<aop:pointcut id="qieidan" expression="execution(* Demo1.service.impl.UserServiceImpl.*(..))"/>
<!--自定义通知-->
<aop:before method="berore" pointcut-ref="qieidan"/>
<aop:after method="after" pointcut-ref="qieidan"/>
</aop:aspect>
</aop:config>
- 注解实现
代理类
@Aspect
public class AnnotationsAop {
//通知类型 和切点
@Before("execution(* Demo1.service.impl.UserServiceImpl.*(..))")
public void before(){
System.out.println("==============方法执行前======================");
}
@After("execution(* Demo1.service.impl.UserServiceImpl.*(..))")
public void after(){
System.out.println("==============方法执行后======================");
}
}
xml配置
<bean id="ann" class="Demo1.aspect.AnnotationsAop"/>
<!--注解实现-->
<!--开启注解 aop自动代理-->
<aop:aspectj-autoproxy/>
测试
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) context.getBean("user");
userService.del();
}
}

浙公网安备 33010602011771号