1. 程式人生 > >spring代理

spring代理

nts ssl return 方式 service cglib system tint del

1.靜態代理

抽象主題 :Subject

public interface Subject {
    public String add();
}

目標對象:ReSubject

public class ReSubject implements Subject {
    public String add() {
        System.out.println("ok!");
        return "";
    }
}

代理對象:Psubject

技術分享
public class Psubject implements Subject {

    private Subject reSubject;

    public Subject getReSubject() {
        return reSubject;
    }

    public void setReSubject(Subject reSubject) {
        this.reSubject = reSubject;
    }

    public String add() {
        System.out.println("開啟!");
        return reSubject.add();
    }
}
技術分享

單側

技術分享
 //靜態代理
    @Test
    public void test12(){
        Subject subject=new ReSubject();
        Psubject psubject=new Psubject();
        psubject.setReSubject(subject);
        psubject.add();
    }
技術分享

2.動態代理

接口

public interface IUserDAO {
    public String add();
    public String edit();
}

技術分享
public class UserDAOImpl implements IUserDAO{
    public String add() {
        System.out.println("add");
        return "add";
    }

    public String edit() {
        System.out.println("edit");
        return "edit";
    }
}
技術分享

單側

技術分享
//動態代理
    @Test
    public void test13(){
       final IUserDAO dao=new UserDAOImpl();
       IUserDAO pp=(IUserDAO) Proxy.newProxyInstance(dao.getClass().getClassLoader(), dao.getClass().getInterfaces(), new InvocationHandler() {
           public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
               System.out.println("開啟");
               method.invoke(dao,args);
               return null;
           }
       });
       pp.add();
       pp.edit();
    }
技術分享

3.cglib動態代理

public class Userservice {
    public void delete(){
        System.out.println("ok");
    }
}

單側(兩種方式)

技術分享
 /*cglib動態代理*/
    @Test
    public void test14(){
        final Userservice servive=new Userservice();
        Enhancer enhancer=new Enhancer();
        enhancer.setSuperclass(servive.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("開啟");
                methodProxy.invoke(servive,objects);
                return null;
            }
        });
       /* enhancer.setCallback(new org.springframework.cglib.proxy.InvocationHandler() {
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                System.out.println("開啟");
                method.invoke(servive,objects);
                return null;
            }
        });*/
        Userservice aa =(Userservice) enhancer.create();
        aa.delete();
    }

spring代理