spring的Arbitrary Method Replacement
作者:互联网
1、替换bean对象中的方法:
(1)原始bean对象MyValueCalculator中的方法computeValue。
package com.it.app.demo;
public class MyValueCalculator {
public String computeValue(String input) {
return input;
}
}
(2)bean对象ReplacementComputeValue的方法(reimplement)去替换。
package com.it.app.demo;
import org.springframework.beans.factory.support.MethodReplacer;
import java.lang.reflect.Method;
public class ReplacementComputeValue implements MethodReplacer {
public Object reimplement(Object o, Method m, Object[] args) throws Throwable {
String input = (String) args[0];
return input.substring(0,3);
}
}
(3)xml对象放到spring容器中配置:
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
<bean id="myValueCalculator" class="com.it.app.demo.MyValueCalculator">
<replaced-method name="computeValue" replacer="replacementComputeValue">
<arg-type>Str</arg-type>
</replaced-method>
</bean>
<bean id="replacementComputeValue" class="com.it.app.demo.ReplacementComputeValue"></bean>
</beans>
(4)执行测试类:
package com.it.app;
import com.it.app.demo.MyValueCalculator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppFive {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-contextFour.xml");
MyValueCalculator myValueCalculator = (MyValueCalculator) context.getBean("myValueCalculator");
System.out.println(myValueCalculator.computeValue("abcdef"));
}
}
(5)执行结果:为abc 替换input输入的abcdef
abc
标签:String,MyValueCalculator,spring,app,Method,input,import,public,Replacement 来源: https://blog.csdn.net/weixin_43947141/article/details/121195112