Spring中的方法注入与构造器注入以及设置器注入不同,设置器注入与构造器注入均是对属性进行设置值,而方法注入则是向Bean注入完整的方法定义。
Spring支持两种形式的方法注入
一:方法替换(使用的是cglib代理实现)
源程序如下:
//一个普通的JavaBean
public class Person {
//人的名字
private String name;
private String action;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getA(){
return action;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
}
配置文件如下:
<bean id="test" class="com.pp.Person">
<property name="Name" value="ppTest"></property>
<property name="Action" value="shopping"></property>
<replaced-method name="getAction" replacer="eat"></replaced-method>
</bean>
<bean id="eat" class="com.pp.Eat"></bean>
从这个配置文件中可以看到又引用了eat这个Bean,这个Bean的定义如下:
import java.lang.reflect.Method;
import org.springframework.beans.factory.support.MethodReplacer;
public class Eat implements MethodReplacer{
@Override
public Object reimplement(Object obj, Method method, Object[] args)
throws Throwable {
Person tmp=(Person)obj;
System.out.println(tmp.getName());
tmp.setAction("eating");
return tmp.getA();
}
}
测试文件如下:
BeanFactory factory=new XmlBeanFactory(new ClassPathResource("person.xml"));
Person tmp=(Person)factory.getBean("test");
System.out.println(tmp.getName());
System.out.println(tmp.getAction());
从打印的结果可以看出的是
tmp.getAction()获取的值已更改了。
二:获取器注入(获取器注入一般用于抽象类,通过获取器注入可以返回某种特定的Bean),Spring利用<lookup-method>配置元素来实现获取器注入,与<replaced-method>一样的是<lookup-method>也是运行时用一个新的实现来替换方法,便我们不需要再编写MethodReplacer类了,这些步骤由Spring帮我们完成。
例子:
//一个普通的JavaBean
public abstract class Person {
//人的名字
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private Sentence sce;
public abstract Sentence getSentence();
}
配置文件如下:
<bean id="test" class="com.pp.Person">
<property name="Name" value="ppTest"></property>
<lookup-method name="getSentence" bean="sce"/>
</bean>
<bean id="sce" class="com.pp.Sentence"></bean>
从这个配置文件可以看到test这个bean中getSentence返回的是sce这个Bean,也就是相当于getSentence这个方法的实现是采用了如下代码的方式:
BeanFactory factory=new XmlBeanFactory(new ClassPathResource("person.xml"));
Sentence sce=(Sentence)factory.getBean("sce");
return sce;
Sentence这个类的具体实现代码如下:
//这是一个普通的类,当然这样设计不好,在此仅为说明一下
public class Sentence{
//类里面的方法,表示每一个人均说的是同样的一句话
public void say() {
System.out.println("Hello");
}
}
测试文件如下:
BeanFactory factory=new XmlBeanFactory(new ClassPathResource("person.xml"));
Person tmp=(Person)factory.getBean("test");
System.out.println(tmp.getName());
tmp.getSentence().say();