Suraj Suraj - 19 days ago 6
Java Question

Setter injection on Interface is taking only the exact name from configurations else throwing exception

I am learning Spring and was trying to implement the following code from the book "Spring in Action". I am not able to understand as to why the Interface property declared with exact name works and else doesn't for a simple Spring application(3.0). Please look into this:

public interface Instrument {
public void play();
}

public interface Performer
{
void perform();
}
public class Saxophone implements Instrument
{
public void play() {
System.out.println("TOOT TOOT TOOT");
}
}
public class Instrumentalist implements Performer
{

private String song;
private Instrument obj; *// not working
// private Instrument instrument; This will work, if replaced* accordingly in the code

public void setSong(String song)
{
this.song=song;
}
public void setInstrument(Instrument instrumen)
{
obj=instrumen;
}
public Instrument getInstrument()
{
return obj;
}
public String getSong()
{
return song;
}
public void perform(){
System.out.println("Playing "+song+" : ");
obj.play();
}
}


The Main class is :

import org.springframework.context.*;
import org.springframework.context.support.*;
class Main
{
public static void main(String ar[])
{
ApplicationContext ctx = new ClassPathXmlApplicationContext("abc.xml");
Performer performer = (Performer) ctx.getBean("kenny");
performer.perform();
}
}


And the configuration are:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
default-init-method="turnONLights" default-destroy-method="turnOFFLights">

<bean id="kenny" class="Instrumentalist">
<property name="song" value="Jingle Bells" />
<property name="obj" ref="saxophone" />
<!-- here also I need to replace obj with "instrument" to make it work -->
</bean>
<bean id="saxophone" class="Saxophone"/>

</beans>


This might be a basic question but yet I am not able to get it.Please help me understand that is it necessary to have the Interface variable have the same name?

Many Thanks

Answer

This part looks incorrect...

<property name="obj" ref="saxophone" />

The value of the name attribute needs to be derived from the setter method; in this case, it looks like you want...

<property name="instrument" ref="saxophone" />

Notice that the characters s-e-t are removed, and the first character -- 'i' -- is lower case.

Comments