系统默认代理模式是使用
/**
* Created by nanji on 2017/1/19.
*/
public interface PersonService {
public void save(String name);
public void update(String name,Integer personid);
public String getPersonName(Integer personid);
/**
* Created by nanji on 2017/1/19.
*/
public class PersonServiceBean implements PersonService {
private String user=null;
public PersonServiceBean() {
}
public PersonServiceBean(String user) {
this.user = user;
}
@Override
public void save(String name) {
System.out.println("xxxx"+name);
}
@Override
public void update(String name, Integer personid) {
System.out.println("我是 update method ");
}
@Override
public String getPersonName(Integer personid) {
System.out.println("我是getPersonname 方法");
return "xxx"+personid;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}
/**
* Created by nanji on 2017/1/19.
*/
public class JDKProxyFactory implements InvocationHandler{
private Object targetObject;
public Object createProxyIntance(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 {
Object result=null;
PersonServiceBean bean=(PersonServiceBean)this.targetObject;
if(bean.getUser()!=null){
method.invoke(targetObject,args);
}
return result;
}
}
@Test
public void ProxyTest(){
JDKProxyFactory factory=new JDKProxyFactory();
PersonService personService= (PersonService) factory.createProxyIntance(new PersonServiceBean("kong"));
personService.save("tian");
}