Spring的replace-method标签
Spring的解析源码
public void parseReplacedMethodSubElements(Element beanEle, MethodOverrides overrides) { NodeList nl = beanEle.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); //仅当在Spring默认bean的子元素下且为
if (isCandidateElement(node) && nodeNameEquals(node, REPLACED_METHOD_ELEMENT)) { Element replacedMethodEle = (Element) node; //提取要替换的旧的方法
String name = replacedMethodEle.getAttribute(NAME_ATTRIBUTE); //提取对应的新的替换方法
String callback = replacedMethodEle.getAttribute(REPLACER_ATTRIBUTE); 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) {
String match = argTypeEle.getAttribute(ARG_TYPE_MATCH_ATTRIBUTE); match = (StringUtils.hasText(match) ? match : DomUtils.getTextValue(argTypeEle)); if (StringUtils.hasText(match)) { replaceOverride.addTypeIdentifier(match); } } replaceOverride.setSource(extractSource(replacedMethodEle)); overrides.addOverride(replaceOverride); } } }
replaced-method的使用
public class LookupMethodBean { public void test(){ System.out.println("原始方法!"); } } public class MethodReplace implements MethodReplacer { public Object reimplement(Object obj, Method method, Object[] args) throws Throwable { System.out.println("方法已经被替换!"); return null; } } <bean name="replacer" class="MethodReplace"> </bean> <bean name="testBean" class="LookupMethodBean"> <replaced-method name="test" replacer="replacer"> </replaced-method > </bean>