AOP(Aspect Orient Programming),一般称为面向切面编程,作为面向工具的一种增补,用于处理惩罚系统中漫衍于各个模块的横切存眷点,好比事务打点、日志、缓存等等。AOP实现的要害在于AOP框架自动建设的AOP署理,AOP署理主要分为静态署理和动态署理,静态署理的代表为AspectJ;而动态署理则以Spring AOP为代表。静态署理是编译期实现,劳务派遣管理系统,动态署理是运行期实现,可想而知前者拥有更好的机能。本文主要先容Spring AOP的两种署理实现机制,JDK动态署理和CGLIB动态署理。
静态署理是编译阶段生成AOP署理类,也就是说生成的字节码就织入了加强后的AOP工具;动态署理则不会修改字节码,而是在内存中姑且生成一个AOP工具,这个AOP工具包括了方针工具的全部要领,而且在特定的切点做了加强处理惩罚,并回调原工具的要领。
Spring AOP中的动态署理主要有两种方法,JDK动态署理和CGLIB动态署理。JDK动态署理通过反射来吸收被署理的类,而且要求被署理的类必需实现一个接口。JDK动态署理的焦点是InvocationHandler接口和Proxy类。
假如方针类没有实现接口,那么Spring AOP会选择利用CGLIB来动态署理方针类。CGLIB(Code Generation Library),是一个代码生成的类库,可以在运行时动态的生成某个类的子类,留意,CGLIB是通过担任的方法做的动态署理,因此假如某个类被标志为final,那么它是无法利用CGLIB做动态署理的,诸如private的要领也是不行以作为切面的。
我们别离通过实例来研究AOP的详细实现。
直接利用Spring AOP
首先界说需要切入的接口和实现。为了简朴起见,界说一个Speakable接口和一个详细的实现类,只有两个要领sayHi()和sayBye()。
public interface Speakable {
void sayHi();
void sayBye();
}
@Service
public class PersonSpring implements Speakable {
@Override
public void sayHi() {
try {
Thread.currentThread().sleep(30);
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println("Hi!!");
}
@Override
public void sayBye() {
try {
Thread.currentThread().sleep(10);
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println("Bye!!");
}
}
接下来我们但愿实现一个记录sayHi()和sayBye()执行时间的成果。
界说一个MethodMonitor类用来记录Method执行时间
public class MethodMonitor {
private long start;
private String method;
public MethodMonitor(String method) {
this.method = method;
System.out.println("begin monitor..");
this.start = System.currentTimeMillis();
}
public void log() {
long elapsedTime = System.currentTimeMillis() - start;
System.out.println("end monitor..");
System.out.println("Method: " + method + ", execution time: " + elapsedTime + " milliseconds.");
}
}
光有这个类照旧不足的,但愿有个静态要领用起来更顺手,像这样
MonitorSession.begin(); doWork(); MonitorSession.end();
说干就干,界说一个MonitorSession
public class MonitorSession {
private static ThreadLocal<MethodMonitor> monitorThreadLocal = new ThreadLocal<>();
public static void begin(String method) {
MethodMonitor logger = new MethodMonitor(method);
monitorThreadLocal.set(logger);
}
public static void end() {
MethodMonitor logger = monitorThreadLocal.get();
logger.log();
}
}
万事具备,接下来只需要我们做好切面的编码,
@Aspect
@Component
public class MonitorAdvice {
@Pointcut("execution (* com.deanwangpro.aop.service.Speakable.*(..))")
public void pointcut() {
}
@Around("pointcut()")
public void around(ProceedingJoinPoint pjp) throws Throwable {
MonitorSession.begin(pjp.getSignature().getName());
pjp.proceed();
MonitorSession.end();
}
}
如何利用?我用了spring boot,写一个启动函数吧。
@SpringBootApplication
public class Application {
@Autowired
private Speakable personSpring;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
// spring aop
System.out.println("******** spring aop ******** ");
personSpring.sayHi();
personSpring.sayBye();
System.exit(0);
};
}
}