ITCAST视频-Spring学习笔记(使用JDK中的Proxy技术实现AOP功能)

 

感谢ITCAST发布的免费视频。

 

AOP—代理对象

 

1.  拦截所有业务方法

2.  判断用户是否有权限,由权限就允许它执行业务方法,没有权限不允许执行业务方法。

 

代理对象创建由两种:静态代理,动态代理

应用的条件是目标对象必须实现接口

 

横切性关注点

Source:

public interface PersonService {

       public void save(String name);

       public void update(String name, Integer personid);

       public String getPersonName(Integer personid);

}

 

public class PersonServiceBean implements PersonService {

       private String user = null;

      

       public PersonServiceBean() {

             

       }

      

       public PersonServiceBean(String user) {

              this.user = user;

       }

      

       public String getPersonName(Integer personid) {

              // TODO Auto-generated method stub

              System.out.println("I'm getPersonName.");

              return "XXX";

       }

 

       public void save(String name) {

              // TODO Auto-generated method stub

              System.out.println("I'm save.");

       }

 

       public void update(String name, Integer personid) {

              // TODO Auto-generated method stub

              System.out.println("I'm update.");

       }

 

       public String getUser() {

              return user;

       }

 

}

 

public class JDKProxyFactory implements InvocationHandler {

       private Object targetObject;

      

       public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

              // TODO Auto-generated method stub

              PersonServiceBean bean = (PersonServiceBean) this.targetObject;

              Object result = null;

             

              if (bean.getUser() != null) {

                     result = method.invoke(targetObject, args);

              }

             

              return result;

       }

      

       public Object createProxyInstance(Object targetObject) {

              this.targetObject = targetObject;

             

              return Proxy.newProxyInstance(this.targetObject.getClass().getClassLoader(),

                            this.targetObject.getClass().getInterfaces(), this);

       }

}

 

public class AOPTest {

       @Test

       public void proxyTest() {

              JDKProxyFactory factory = new JDKProxyFactory();

              PersonService service = (PersonService) factory.createProxyInstance(new PersonServiceBean());

             

              service.getPersonName(1);

       }

}

你可能感兴趣的:(spring)