spring容器标签解析之replaced-method

上节看了lookup-method的简单的case和解析过程,大家对lookup-method有了一定的了解,接下来看replaced-method的解析过程,看之前我们先实践一下replace的demo,看代码:

首先创建一个实体类,代码如下:

public class MyBean {

public void disPlay(){


    System.out.println("me is原来的method");
}

实现过程

package com.sgcc.bean;

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

import java.lang.reflect.Method;

public class MyBeanReplacer implements MethodReplacer {
public Object reimplement(Object obj, Method method, Object[] args) throws Throwable {

    System.out.println("我替换了原来的method!");
    return null;
}

再来看配置文件





    



再来看测试结果

package com.sgcc.bean;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

public static void main(String[] args) {

    ApplicationContext context = new ClassPathXmlApplicationContext("replaceMethod.xml");
    MyBean myBean = (MyBean) context.getBean("myBean");
    myBean.disPlay();
}

运行结果如下图:


spring容器标签解析之replaced-method_第1张图片
微信截图_20190616094830.png

从配置到结果来看,成功的替换了原来的方法,这就是它的简单的用法,接着我们spring是对其如何解析的过程,还是要追溯到BeanDefinitionParserDelegate#parseReplacedMethodSubElements()方法入口,我们来看代码:

public void parseReplacedMethodSubElements(Element beanEle, MethodOverrides overrides) {
    //获取所有的子元素
    NodeList nl = beanEle.getChildNodes();
    //遍历只拿replaced-method元素
    for (int i = 0; i < nl.getLength(); i++) {
        Node node = nl.item(i);
        if (isCandidateElement(node) && nodeNameEquals(node, REPLACED_METHOD_ELEMENT)) {
            Element replacedMethodEle = (Element) node;
            //获取name和replacer属性
            String name = replacedMethodEle.getAttribute(NAME_ATTRIBUTE);
            String callback = replacedMethodEle.getAttribute(REPLACER_ATTRIBUTE);
            //构建一个ReplaceOverride实例
            ReplaceOverride replaceOverride = new ReplaceOverride(name, callback);
            // Look for arg-type match elements.
            //匹配所有的子元素
            List argTypeEles = DomUtils.getChildElementsByTagName(replacedMethodEle, ARG_TYPE_ELEMENT);
            for (Element argTypeEle : argTypeEles) {
                //获取属性为match的
                String match = argTypeEle.getAttribute(ARG_TYPE_MATCH_ATTRIBUTE);
                //判null,若为null通过DomUtils.getTextValue(argTypeEle)取值,不为null还是match
                match = (StringUtils.hasText(match) ? match : DomUtils.getTextValue(argTypeEle));
                //保存
                if (StringUtils.hasText(match)) {
                    replaceOverride.addTypeIdentifier(match);
                }
            }
            replaceOverride.setSource(extractSource(replacedMethodEle));
            overrides.addOverride(replaceOverride);
        }
    }
}

上述就是简单的对replaced-method的解析过程,这里就不多说了

你可能感兴趣的:(spring容器标签解析之replaced-method)