美文网首页
lookup-method和replaced-method使用

lookup-method和replaced-method使用

作者: 守住阳光 | 来源:发表于2018-09-26 16:14 被阅读0次

    一、概述

            lookup-method 和 replaced-method 是在 xml 配置bean的时候的可选配置,其中lookup-method可以声明方法返回某个特定的bean,replaced-method可以改变某个方法甚至改变方法的逻辑。

    二、使用

            定义一个User接口,和接口的两个实现Teacher和Student。

            public  interface   User{

                     public  void   showMe();

            }

            public  class  Teacher  implements  User{

                    @Override

                    public  void  showMe(){

                        System.out.println("I am a Teacher");

                    }

            }

            public  class  Student implements   User{

                    @Override

                    public  void  showMe(){

                        System.out.println("I am a Student");

                    }

            }

            测试用的bean:

            public  abstract  class  MyTestBean{

                 //用于测试lookup-method

                 public  abstract  User  getUserBean();

                 //用于测试replace-method

                 public  void  changedMethod(){

                      System.out.println("Origin method in MyTestBean run");

                  }

            }

            这里的getUserBean返回一个User的实例。用于测试lookup-method。

            为了同时测试replace-method 这里定义一个Replacer类:

            public  class  Replacer  implements  MethodReplacer{

                    @Override

                    public  Object  reimplement(Object obj, Method method, Object[] args)throws  Throwable{

                            System.out.println("replacer method run");

                            return  null;

                    }

             }

            Replacer类需要实现MethodReplacer接口,该接口包含一个reimplement方法,这个方法最后将会代替被替代的方法来执行,同时参数中提供了相应的Object和Method以及参数等,明显允许我们利用反射的方式调用原来的方法。

           xml配置

    < bean id="myTestBean" class="io.spring.test.MyTestBean" >

         <lookup-method name="getUserBean" bean="student" />

         <replaced-method name="changedMethod" replacer="replacer" />

    </bean>

    <bean id="teacher" class="io.spring.test.Teacher"   />

    <bean id="student" class="io.spring.test.Student" / >

    <bean id="replacer" class="io.spring.test.Replacer" />

            编写测试类:

            public  class  MyBeanTest{

                 @Test

                 public  void  testMyBean(){

                        ConfigurableApplicationContext context =newClassPathXmlApplicationContext("spring.xml");

                        MyTestBean bean = (MyTestBean) context.getBean("myTestBean");

                        bean.getUserBean().showMe();

                        bean.changedMethod();

                }

            }

            执行结果:

    I am a Student

    replacer method run

            

    相关文章

      网友评论

          本文标题:lookup-method和replaced-method使用

          本文链接:https://www.haomeiwen.com/subject/vlzdoftx.html