一、原始bean定义
package cn.edu.tju.study.service.anno.domain;public class MyValueCalculator {public String computeValue(String input) {return "you inputted: " + input;}// some other methods...
}
二、replace bean定义
package cn.edu.tju.study.service.anno.domain;import org.springframework.beans.factory.support.MethodReplacer;import java.lang.reflect.Method;
import java.util.Locale;public class ReplacementComputeValue implements MethodReplacer {public Object reimplement(Object o, Method m, Object[] args) throws Throwable {String input = (String) args[0];return input.toUpperCase();}
}
三、配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:c="http://www.springframework.org/schema/c"xmlns:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beanshttps://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="myValueCalculator" class="cn.edu.tju.study.service.anno.domain.MyValueCalculator"><!-- arbitrary method replacement --><replaced-method name="computeValue" replacer="replacementComputeValue"><arg-type>String</arg-type></replaced-method></bean><bean id="replacementComputeValue" class="cn.edu.tju.study.service.anno.domain.ReplacementComputeValue"/></beans>
四、主类:
package cn.edu.tju;import cn.edu.tju.study.service.anno.domain.MyValueCalculator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Start17 {public static void main(String[] args) {ApplicationContext applicationContext = newClassPathXmlApplicationContext("beans17.xml");MyValueCalculator result = applicationContext.getBean("myValueCalculator", MyValueCalculator.class);System.out.println(result.computeValue("hello"));}
}
五、执行结果: