spring容器标签解析之replaced-method
2019-06-17 本文已影响0人
会上树的程序猿
上节看了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;
}
再来看配置文件
<?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="myBean" class="com.sgcc.bean.MyBean">
<replaced-method name="disPlay" replacer="replacer"/>
</bean>
<bean id="replacer" class="com.sgcc.bean.MyBeanReplacer"/>
</beans>
再来看测试结果
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();
}
运行结果如下图:
微信截图_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<Element> 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的解析过程,这里就不多说了