ConstructorProperties注释不起作用

时间:2014-04-15 01:37:50

标签: java spring dependency-injection annotations inversion-of-control

我正在尝试使用基于构造函数的依赖注入来获取bean实例。但它不断抛出 org.springframework.beans.factory.UnsatisfiedDependencyException

错误消息:在类路径资源[bean.xml]中定义名称为'bean1'的bean时出错:通过构造函数参数表示不满意的依赖关系,索引1的类型为[java.lang.String]:不明确的构造函数参数类型 - 确实您将正确的bean引用指定为构造函数参数吗?

以下是我的简单代码:

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>

有人可以帮忙弄明白问题是什么吗? 提前谢谢!

1 个答案:

答案 0 :(得分:2)

小错字:-),应该是xml中的ultimateAnswer,而不是ultimateanswer