[maven + spring]SpringInAction方法替换<replaced-method>

引用

Spring 方法替换例子

1.sec3.xml中
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-4.0.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
    <bean id="tigerReplacer" class="com.lh.springtest02.section3.TigerReplacer" />       
	<bean id="magicbox" class="com.lh.springtest02.section3.MagicBoxImpl">
		<replaced-method name="getContents" replacer="tigerReplacer"/>
	</bean>
	<bean id="harry" class="com.lh.springtest02.section3.Magician">
		<property name="magicWords" value="Bippity boppity boo" />
		<property name="magicBox" ref="magicbox" />
	</bean>
</beans>    

2.替换方法实现
import java.lang.reflect.Method;
import org.springframework.beans.factory.support.MethodReplacer;
public class TigerReplacer implements MethodReplacer{
	public Object reimplement(Object obj, Method method, Object[] args)
			throws Throwable {
		return "A ferocious tiger";
	}
}

3.MagicBoxImpl.java
public class MagicBoxImpl implements MagicBox{
	public MagicBoxImpl() {
	}
	public String getContents() {
		return "A Beautiful assistant";
	}
}

4.Magician.java
public class Magician implements Performer{
	private MagicBox magicBox;
	private String magicWords;
	public void perform() {
		System.out.println(magicWords);
		System.out.println("The magic box contains ...");
		System.out.println(magicBox.getContents());
	}
	public void setMagicBox(MagicBox magicBox) {
		this.magicBox = magicBox;
	}
	public void setMagicWords(String magicWords) {
		this.magicWords = magicWords;
	}
}

5.Bean测试
ApplicationContext ac = new ClassPathXmlApplicationContext("section3/sec3.xml");
Magician mc = (Magician)ac.getBean("harry");
mc.perform();

猜你喜欢

转载自lianghua840716.iteye.com/blog/2038012
今日推荐