Wednesday, August 1, 2012

Spring Method Replacer


Method Replacer Implementation:
Greeting.java:
package com.lnn.method.replacer;

public interface Greeting {
      public String greet();
}
GreetingImpl.java:
package com.lnn.method.replacer;

public class GreetingImpl implements Greeting {
      @Override
      public String greet() {
            return "Good Morning!";
      }
}

GreetingReplacer.java:
package com.lnn.method.replacer;

import java.lang.reflect.Method;

import org.springframework.beans.factory.support.MethodReplacer;

public class GreetingReplacer implements MethodReplacer {

      @Override
      public Object reimplement(Object obj, Method method, Object[] args) throws Throwable {
            return "Good Night!";
      }

}

replacer.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
      <bean id="greeting" class="com.lnn.method.replacer.GreetingImpl">
            <replaced-method name="greet" replacer="greetingReplacer" />
      </bean>
      <bean id="greetingReplacer" class="com.lnn.method.replacer.GreetingReplacer" /> 
</beans>

Test.java:
package com.lnn.method.replacer;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
      public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("replacer.xml");
            Greeting greeting = context.getBean("greeting", Greeting.class);
            System.out.println(greeting.greet());
      }
}

No comments:

Post a Comment