`
shameant
  • 浏览: 57449 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics