spring源码学习---replaced-method的使用

作为开发人员,我觉得直接看例子更好:
1、bean配置文件

<?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-4.0.xsd"
       default-lazy-init="true">
    <description>bean配置</description>

    <bean id="myBean" class="com.zzr.web.test.MyBean">
        <replaced-method name="display" replacer="replacer"/>
    </bean>

    <bean id="replacer" class="com.zzr.web.test.MyBeanReplacer"/>
</beans>

2、MyBean代码

package com.zzr.web.test;

/**
 * Created by sjgtw-zzr on 2018/5/17.
 */
public class MyBean {
    public void display(){
        System.out.println("我是原来的方法");
    }
}

3、MyBeanReplacer的代码

package com.zzr.web.test;

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

import java.lang.reflect.Method;

/**
 * Created by sjgtw-zzr on 2018/5/17.
 */
public class MyBeanReplacer implements MethodReplacer{
    @Override
    public Object reimplement(Object obj, Method method, Object[] args) throws Throwable {
        System.out.println("我替换了原来的方法");
        return null;
    }
}

4、测试代码

package com.zzr.web.test;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

/**
 * Created by sjgtw-zzr on 2018/5/17.
 */
public class Main {
    public static void main(String[] args) {
        BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("bean.xml"));
        MyBean myBean = (MyBean) beanFactory.getBean("myBean");
        myBean.display();
    }
}

5、输出结果

我替换了原来的方法

使用场景:动态替换原有的业务逻辑

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值