SpringAOP
- 如果目标对象实现了接口,则默认采用JDK动态代理
- 如果目标对象没有实现接口,则采用Cglib进行动态代理
- 如果目标对象实现了接口,且强制cglib代理,则使用cglib代理
链式调用AOP
chain.png例子
public abstract class Handler {
private Handler sucessor;
public Handler getSucessor() {
return sucessor;
}
public void setSucessor(Handler sucessor) {
this.sucessor = sucessor;
}
public void execute(){
handleProcess();
if(sucessor != null){
sucessor.execute();
}
}
protected abstract void handleProcess();
}
客户端调用
public class Client {
static class HandlerA extends Handler{
@Override
protected void handleProcess() {
System.out.println("handle by a");
}
}
static class HandlerB extends Handler{
@Override
protected void handleProcess() {
System.out.println("handle by b");
}
}
static class HandlerC extends Handler{
@Override
protected void handleProcess() {
System.out.println("handle by c");
}
}
public static void main(String[] args){
Handler handlerA = new HandlerA();
Handler handlerB = new HandlerB();
Handler handlerC = new HandlerC();
handlerA.setSucessor(handlerB);
handlerB.setSucessor(handlerC);
handlerA.execute();
}
}
改造
public abstract class ChainHandler {
public void execute(Chain chain){
handleProcess();
chain.proceed();
}
protected abstract void handleProcess();
}
public class Chain {
private List<ChainHandler> handlers;
private int index = 0;
public Chain(List<ChainHandler> handlers) {
this.handlers = handlers;
}
public void proceed(){
if(index >= handlers.size()){
return ;
}
handlers.get(index++).execute(this);
}
}
客户端
public class ChainClient {
static class ChainHandlerA extends ChainHandler{
@Override
protected void handleProcess() {
System.out.println("handle by chain a");
}
}
static class ChainHandlerB extends ChainHandler{
@Override
protected void handleProcess() {
System.out.println("handle by chain b");
}
}
static class ChainHandlerC extends ChainHandler{
@Override
protected void handleProcess() {
System.out.println("handle by chain c");
}
}
public static void main(String[] args){
List<ChainHandler> handlers = Arrays.asList(
new ChainHandlerA(),
new ChainHandlerB(),
new ChainHandlerC()
);
Chain chain = new Chain(handlers);
chain.proceed();
}
}
##SpringAOP中AOP责任链
![图片.png](https://img.haomeiwen.com/i6720201/b74dfe8179d6e96f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
网友评论