一、靜態代理:
靜態代理要求代理對象和被代理對象實現同一個對象。
IUserService:
package com.swjs.aop.serivce;

import java.util.List;

/**
* @author jason
*
*/
public interface IUserService {
List getUserList();
}
被代理類UserService:
package com.swjs.aop.serivce;

import java.util.List;

/**
* @author jason
*
*/
public class UserService implements IUserService {

public List getUserList() {
System.out.println("get Userlist");
return null;
}

}
代理類:
package com.swjs.aop.serivce;

import java.util.List;

/**
* @author jason
*
*/
public class SecureProxy implements IUserService{

private IUserService userService;

public SecureProxy(IUserService userService) {
super();
this.userService = userService;
}
public List getUserList()
{
System.out.println("身份檢查");
userService.getUserList();
System.out.println("事務提交");
return null;
}
}
測試類:
package com.swjs.aop.serivce;

/**
* @author jason
*
*/
public class StaticProxyTest {

/**
* @param args
*/
public static void main(String[] args) {
IUserService userService = new UserService();
SecureProxy proxy = new SecureProxy(userService);
proxy.getUserList();
}
}
顯示結果:
身份檢查
get Userlist
事務提交
二:動態代理
接口
public interface IUserService {

public void getUserList(int start, int limit);
}
業務方法:
public class UserService implements IUserService {

public void getUserList(int start, int limit) {
System.out.println("start: " + start + " limit: " + limit );
System.out.println("get user List");
}
}
處理器:
public class SecureHandler implements InvocationHandler {

private IUserService service;
public SecureHandler(IUserService service) {
super();
this.service = service;
}


public Object invoke(Object proxy, Method method, Object[] arg)
throws Throwable {
System.out.println("trac begin");
System.out.println(arg.length);
for(int i = 0; i < arg.length; i++)
{
System.out.println(arg[i]);
}
method.invoke(service, arg);
System.out.println("trac end");
return null;
}

}
測試類:
public class DynamicProxyTest {

public static void main(String[] args)
{
IUserService service = new UserService();
SecureHandler handler = new SecureHandler(service);
IUserService serv = (IUserService)Proxy.newProxyInstance(service.getClass().getClassLoader(),
service.getClass().getInterfaces(), handler);
serv.getUserList(0,10);
}
}
顯示結果:
trac begin
2
0
10
start: 0 limit: 10
get user List
trac end
靜態代理要求代理對象和被代理對象實現同一個對象。
IUserService:












被代理類UserService:
















代理類:

























測試類:

















顯示結果:



二:動態代理
接口




業務方法:







處理器:

























測試類:











顯示結果:







