Spring文档苦读【3】【方法替换】

前言

Spring中,通过CGLIB编织注入的方式,修改方法内容,是用户可以更好的管理他们的Bean的方法。

使用方式

1,创建待替换的方法以及类

 1 public class MyValueCaculator {
 2     /**
 3      * 自动加一
 4      * @param input
 5      * @return
 6      */
 7     public String computeValue(String input) {
 8         BigDecimal big = new BigDecimal(input);
 9         big.add(new BigDecimal("1"));
10         return big.toString();
11     }
12     
13     public String computeValue2(String input) {
14         return computeValue(input);
15     }
16 }

2,创建替换的方法(需要继承接口MethodReplacer)

 1 public class ReplacementComputeValue implements MethodReplacer {
 2     
 3     /**
 4      * 自动加二
 5      */
 6     public Object reimplement(Object obj, Method method, Object[] args)
 7             throws Throwable {
 8         String input = (String)args[0];
 9         return new BigDecimal(input).add(new BigDecimal("2")).toString();
10     }
11 
12 }

3,XML配置

1     <bean id="myValueCaculator" class="com.may.core.xml.methodreplacer.MyValueCaculator">
2         <replaced-method name="computeValue" replacer="replacementComputeValue">
3             <arg-type>String</arg-type>
4         </replaced-method>
5     </bean>
6     <bean id="replacementComputeValue" class="com.may.core.xml.methodreplacer.ReplacementComputeValue"></bean>

4,测试

 1 @RunWith(SpringRunner.class)
 2 @ContextConfiguration("/applicationContext.xml")
 3 public class MyValueCaculatorTest {
 4     @Autowired
 5     private ApplicationContext applicationContext;
 6     @Test
 7     public void testComputeValue() {
 8         MyValueCaculator caculator = applicationContext.getBean(MyValueCaculator.class);
 9         Assert.assertEquals(caculator.computeValue2("1234"), "1236");
10     }
11 }

 

posted on 2016-12-23 16:50  源码解析  阅读(142)  评论(0编辑  收藏  举报

导航