getter injection


Code:

public abstract class Instrumentalist implements Performer {

public Instrumentalist() {}

public void perform() throws PerformanceException {
System.out.print("Playing " + song + " : ");
getInstrument().play();
}

private String song;
public void setSong(String song) {
this.song = song;
}

public abstract Instrument getInstrument();

}

 

XML:

<bean id="stevie" class="com.springinaction.springidol.Instrumentalist">
<lookup-method name="getInstrument" bean="guitar" />
<property name="song" value="Greensleeves" />
</bean>

<bean id="guitar" class="com.springinaction.springidol.Guitar"
scope="prototype" />

  Notice: Bean "guitar" must be prototype otherwise always same instance will be returned

 

As with <replaced-method>, the name attribute of <lookup-method> indicates the method that is to be replaced. Here we’re replacing the getInstrument() method. The bean attribute refers to a bean that should be returned when getInstrument() is called. In this case, we’re wiring in the bean whose id is guitar. As a result, the getInstrument() method is effectively overridden as follows:

 

 

public Instrument getInstrument() {
ApplicationContext ctx = …;
return (Instrument) ctx.getBean("guitar");
}
 


On its own, getter injection is just a reversal of setter injection. However, it makes a difference when the referenced bean is prototype scoped:Even though it’s prototype scoped, the guitar method would only be injected  once into a property if we were using setter injection. By injecting it into the get-
Instrument() method through getter injection, however, we ensure that every call to getInstrument() will return a different guitar. This can come in handy if a guitarist breaks a string in the middle of a performance and needs a freshly stringed instrument.


You should be aware that although we used <lookup-method> to perform getter injection on the getInstrument() method, there’s nothing about <lookupmethod> that requires that the replaced method actually be a getter method (i.e., one whose name starts with get). Any non-void method is a candidate for replacement with <lookup-method>.


It’s important to note that while method injection allows you to change a method’s implementation, it’s not capable of replacing a method’s signature. The parameters and return type must

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值