Question

I'm trying to get a bean instance using Constructor-based dependency injection. But it keeps throwing org.springframework.beans.factory.UnsatisfiedDependencyException.

Error message: Error creating bean with name 'bean1' defined in class path resource [bean.xml]: Unsatisfied dependency expressed through constructor argument with index 1 of type [java.lang.String]: Ambiguous constructor argument types - did you specify the correct bean references as constructor arguments?

Following is my simple code:

Bean1.java

package com.example.bean
import java.beans.ConstructorProperties;

public class Bean1 {

    private int years;

    private String ultimateAnswer;

    @ConstructorProperties({"years", "ultimateAnswer"})
    public Bean1(int years, String ultimateAnswer) {
        this.years = years;
        this.ultimateAnswer = ultimateAnswer;
    }

    public int getYears() {
        return years;
    }    
    public void setYears(int years) {
        this.years = years;
    }
    public String getUltimateAnswer() {
        return ultimateAnswer;
    }
    public void setUltimateAnswer(String ultimateAnswer) {
        this.ultimateAnswer = ultimateAnswer;
    }

    public void print() {
        System.out.println("years:" + years + ", ultimateAnswer:" + ultimateAnswer);
    }
}

TestApp.java

package com.example.app;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.example.bean.Bean1;


public class TestApp {

    @SuppressWarnings("resource")
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"bean.xml"});
        Bean1 bean1 = context.getBean("bean1",Bean1.class);
       bean1.print();

    }
}

bean.xml

<?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.xsd">

    <bean id="bean1" class="com.example.bean.Bean1">
        <constructor-arg name="years" value="7500000"/>
        <constructor-arg name="ultimateanswer" value="42"/>
    </bean>
</beans>

Could anybody help to figure it out what's the problem? Thanks in advance!

Was it helpful?

Solution

Minor typo :-), should be ultimateAnswer in your xml, not ultimateanswer

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top