1、 创建一个被拦截对象接口peopleService (横切性关注点):
package com.wxy.service;
public interface PeopleService {
public void save(String name);
public void update(String name, Integer peopleId);
public String getPeopleName(Integer peopleId);
}
2、 实现被拦截对象接口
package com.wxy.service.impl;
import com.wxy.service.PeopleService;
public class PeopleServiceBean implements PeopleService {
private String user = null;
public PeopleServiceBean() {
}
public PeopleServiceBean(String user) {
this.setUser(user);
}
@Override
public String getPeopleName(Integer peopleId) {
System.out.println("我是getPeopleName()方法");
return "wxy";
}
@Override
public void save(String name) {
System.out.println("我是save()方法,save:" + name);
}
@Override
public void update(String name, Integer peopleId) {
System.out.println("我是update()方法");
}
/**
* @param user the user to set
*/
public void setUser(String user) {
this.user = user;
}
/**
* @return the user
*/
public String getUser() {
return user;
}
}
3、拦截所有的业务方法,
判断用户是否有权限,有权限就允许执行业务方法,没有权限则不允许执行业务方法(是否有权限是根据user是否为null为依据的)。
为目标对象创建动态代理类的类proxy(在jdk中的反射中):
package com.wxy.aop;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import com.wxy.service.impl.PeopleServiceBean;
/**
* 创建代理工厂
* 当客户端调用代理对象的业务方法时,代理对象执行invoke方法,invoke方法把调用委派给targetObject
* 相当于调用目标对象的方法,在invoke方法委派前判断权限,实现方法的拦截
* @creator xiaoyu.wang
* @create-time 2011-8-18 上午08:57:30
* @revision $Id
*/
public class JDKProxyFactory implements InvocationHandler {
private Object targetObject;
public Object createProxyInstance(Object targetObject) {
this.targetObject = targetObject;
return Proxy.newProxyInstance(this.targetObject.getClass().getClassLoader(),
this.targetObject.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
PeopleServiceBean bean = (PeopleServiceBean) this.targetObject;//被代理对象
Object result = null;
if (bean.getUser() != null) {//有权限,user不为null
result = method.invoke(targetObject, args);
}
return result;
}
/**
* @param targetObject the targetObject to set
*/
public void setTargetObject(Object targetObject) {
this.targetObject = targetObject;
}
/**
* @return the targetObject
*/
public Object getTargetObject() {
return targetObject;
}
}
4、测试:
public class AOPTest {
public static void main(String[] args) {
JDKProxyFactory factory = new JDKProxyFactory();
PeopleService service = (PeopleService) factory.createProxyInstance(new PeopleServiceBean(
"wxy"));
service.save("wxy");
}
}
测试结果:
我是save()方法,save:wxy