Suraj Suraj - 1 year ago 82
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)
public void setInstrument(Instrument instrumen)
public Instrument getInstrument()
return obj;
public String getSong()
return song;
public void perform(){
System.out.println("Playing "+song+" : ");;

The Main class is :

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

And the configuration are:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
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 id="saxophone" class="Saxophone"/>


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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download