第九讲:AOP实现之ajc编辑器
目录
第九讲:AOP实现之ajc编辑器
学习目标
一、AOP的另一种实现及原理
学习目标
AOP的另一种实现及原理(编译期间)
一、AOP的另一种实现及原理
一般我们说Spring的AOP都是代理增强,其实这不是完全正确的,
还有一种是利用插件aspectj直接修改class文件来实现增强
一般我们说Spring的AOP都是代理增强,其实这不是完全正确的,
还有一种是利用插件aspectj直接修改class文件来实现增强
准备 service
package com.itheima.service;
import com.itheima.aop.MyAspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class MyService {
private static final Logger log = LoggerFactory.getLogger(MyService.class);
public static void foo() {
log.debug("foo()");
}
}
这里要注意的是,这个aspectj类是没有交给Spring容器进行管理的
package com.itheima.aop;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Aspect // ⬅️注意此切面并未被 Spring 管理
public class MyAspect {
private static final Logger log = LoggerFactory.getLogger(MyAspect.class);
@Before("execution(* com.itheima.service.MyService.foo())")
public void before() {
log.debug("before()");
}
}
package com.itheima;
import com.itheima.service.MyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class A09 {
private static final Logger log = LoggerFactory.getLogger(A09.class);
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(A09.class, args);
MyService service = context.getBean(MyService.class);
log.debug("service class: {}", service.getClass());
service.foo();
context.close();
}
}
最后结果是
这是因为我们使用的是aspectj插件进行的实现,因此无需容器也可以进行增强
注意这里要实现这个功能 要引入坐标
org.codehaus.mojo aspectj-maven-plugin1.14.0 1.8 8 8 true true ignore UTF-8 compile test-compile
1. 版本选择了 java 8, 因为目前的 aspectj-maven-plugin 1.14.0 最高只支持到 java 16 2. 一定要用 maven 的 compile 来编译, idea 不会调用 ajc 编译器
这是因为我们使用的是aspectj插件进行的实现,因此无需容器也可以进行增强
因为这是因为插件直接修改的是.class文件的字节码
因此 静态类或不用容器直接调用对象的方法也可以执行
这就是Aop实现的另一种原理ajc编译器
主要优点就是:可以实现静态方法的增强
不适用容器也可以进行增强



