一、原始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/beans
https://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>
四、主类:文章来源:https://www.toymoban.com/news/detail-658557.html
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 = new
ClassPathXmlApplicationContext("beans17.xml");
MyValueCalculator result = applicationContext.getBean("myValueCalculator", MyValueCalculator.class);
System.out.println(result.computeValue("hello"));
}
}
五、执行结果:
文章来源地址https://www.toymoban.com/news/detail-658557.html
到了这里,关于Spring 6.0官方文档示例(24): replace-method的用法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!