1. 程式人生 > >通過代理實現許可權控制

通過代理實現許可權控制

許可權控制在很多系統中都會用到,其實實現許可權控制方法有很多,這裡給大家介紹一下通過代理模式實現許可權控制。Spring中的AOP、Apache的shiro開源專案,其實都是基於此的。

1、實體類Person.java

public class Person {
    private String name;
    private String password;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public
String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }

2、業務邏輯層介面及實現類
這裡的業務邏輯層介面就是代理模式中的抽象物件角色,它的實現類就是真實物件。

import java.util.List;
import java.util.Map;

public interface IPersonService {
    Integer savePerson(Person person);
    void
updatePerson(Person person); List<Person> findPersonList(Map<String,Object> param); }
import java.util.List;
import java.util.Map;

public class PersonServiceImpl implements IPersonService{

    @Override
    public Integer savePerson(Person person) {
        return null;
    }

    @Override
public void updatePerson(Person person) { } @Override public List<Person> findPersonList(Map<String, Object> param) { return null; } }

3、建立代理類的工廠

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ServiceProxyFactory implements InvocationHandler {
    private  Object service = null;//真實物件

    public ServiceProxyFactory(){

    }
    public Object createServiceProxy(Object obj){
        this.service = obj;
        return Proxy.newProxyInstance(this.service.getClass().getClassLoader(), 
                this.service.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        PersonServiceImpl personService = (PersonServiceImpl)service;
        if(......){//判斷當前登入的使用者有沒有許可權
            return method.invoke(service, args);
        }
        return null;
    }
}

4、使用代理類

public class TestProxy{
    public static void main(String[] args){
        IPersonService service = new PersonServiceImpl();//真實物件
        ServiceProxyFactory proxyFactory = new ServiceProxyFactory();
        IPersonService  proxyService = proxyFactory.createServiceProxy(service);//代理物件
        proxyService.savePerson();//使用代理物件儲存Person,當代理物件執行savePerson()方法時,會呼叫proxyFactory的invoke()方法,因為在建立代理物件時,Proxy.newProxyInstance()方法的第三個引數中傳入了一個ServiceProxyFactory的例項。在invoke方法內部就可以進行許可權控制,檢視當前使用者有沒有許可權進行savePerson()操作。
    }
}