面向切面编程AOP
前言
AOP(Aspect Orient Programming),面向切面编程。
切面:公共的,通用的,重复的功能称为切面,面向切面编程就是将切面提取出来,单独开发,在需要调用的方法中通过动态代理的方式进行织入.
本文通过图书购买演示AOP不同版本发展
业务:图书购买业务
切面:事务
提示:以下是本篇文章正文内容,下面案例可供参考
一、业务和切面紧耦合.
public class Book {
public void buy(){
try {
System.out.println("事务开启----");
System.out.println("图书购买业务启动----");
System.out.println("事务提交---");
} catch (Exception e) {
System.out.println("事务回滚---");
}
}
}
二、使用子类代理的方式拆分业务和切面
父类FBookServiceImpl:
--------父类中只有干干净净的业务
public class FBookServiceImpl {
public void buy(){
System.out.println("图书购买功能实现---");
}
}
子类ZBookServiceImpl
public class ZBookServiceImpl extends FBookServiceImpl{
@Override
public void buy() {
try {
//事务切面
System.out.println("事务开启---");
//事务实现
super.buy();
//事务切面
System.out.println("事务提交---");
} catch (Exception e) {
System.out.println("事务回滚");
}
}
}
三.使用静态代理拆分业务和切面.
业务和业务接口已拆分.此时切面紧耦合在业务中.
跳过
四.使用静态代理拆分业务和业务接口,切面和切面接口
目录结构
静态代理
public class Agent implements Service{
//传入业务对象 切面对象
Service target;
AOP aop;
public Agent(Service target,AOP aop){
this.target=target;
this.aop=aop;
}
@Override
public void buy() {
try {
//切面
aop.before();
//业务
target.buy();
//切面
aop.after();
} catch (Exception e) {
aop.exception();
}
}
}
五. 使用动态代理
相对于静态代理四,只更改了代理类Agent
public class ProxyFactory {
public static Object getAgent(Service grant, AOP aop){
return Proxy.newProxyInstance(
//加载类
grant.getClass().getClassLoader(),
//加载接口
grant.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(
//生成代理对象
Object proxy,
//正在被调用的目标方法buy(),show()
Method method,
//目标方法参数
Object[] args) throws Throwable {
Object obj = null;
try {
aop.before();
obj = method.invoke(grant, args);
aop.after();
} catch (Exception e) {
aop.exception();
}
return obj;
}
}
);
}
}