Issue
Here I am trying to do setter injection of two properties
I have two interface / class pair - dependency
and dependecySecond
-
IDependency.java -
public interface IDependency {
public void printDependency();
}
IDependencySecond.java -
public interface IDependencySecond {
public void printSecondDependency();
}
Dependency.java -
public class Dependency implements IDependency {
Dependency() {
System.out.println("Inside dependency constructor");
}
@Override
public void printDependency() {
System.out.println("I am dependency");
}
}
DependencySecond.java -
public class DependencySecond implements IDependencySecond {
DependencySecond() {
System.out.println("Inside second dependency constructor");
}
@Override
public void printSecondDependency() {
System.out.println("I am second depedency");
}
}
Now I have IGame / BaseBallGame interface / class pair -
IGame.java -
public interface IGame {
public void printDependency();
public void playGame();
}
BaseBallGame.java -
public class BaseBallGame implements IGame {
private IDependency dependency;
private IDependencySecond dependencySecond;
BaseBallGame(){
System.out.println("Inside baseball game constructor");
}
public void setDependency(IDependency dependency) {
this.dependency = dependency;
}
public void setDependencySecond(IDependencySecond dependencySecond) {
this.dependencySecond = dependencySecond;
}
@Override
public void printDependency() {
dependency.printDependency();
}
@Override
public void playGame() {
System.out.println("Playing baseball");
}
}
Now, at first I have the following bean code -
<bean id="dependency"
class="com.lonelychild.springdemo.Dependency">
</bean>
<bean id="dependency2"
class="com.lonelychild.springdemo.DependencySecond">
</bean>
<bean id="game"
class="com.lonelychild.springdemo.BaseBallGame">
<property name="dependency" ref="dependency"></property>
</bean>
and I have following main code -
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
IGame game = context.getBean("game", IGame.class);
game.printDependency();
game.playGame();
context.close();
It runs without error
but when I add "dependencySecond" in bean -
<bean id="game"
class="com.lonelychild.springdemo.BaseBallGame">
<property name="dependency" ref="dependency"></property>
<property name="dependency2" ref="dependency2"></property>
</bean>
I get
illegal depedencySecond setter method exception
So how can I add the second property?
Solution
The name of your property is work. It must mstach with the property name in the class, so:
<property name="dependency2" ref="dependency2">
must be:
<property name="dependencySecond" ref="dependency2">
BTW: Stop using the old outdated xml configuration. Switch to the modern java based configuration.
Answered By - Jens
Answer Checked By - Cary Denson (JavaFixing Admin)