我通过构造器注入,并且给构造参数指定了类型,但是运行时报错。
代码:
[code="java"]package com.alpha.spring.ch4;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class ConstructorConfusion {
private String message;
public ConstructorConfusion(String message, int number) {
System.out.println("ConstructorConfusion(String message, int number) is called");
this.message = message + Integer.toString(number);
}
public String toString() {
return message;
}
public static void main(String[] args) {
XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("applicationContext.xml"));
ConstructorConfusion cc = (ConstructorConfusion)factory.getBean("constructorConfusion");
System.out.println(cc);
}
}
[/code]
xml配置文件:
[code="java"]<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
hello world
20
[/code]
运行代码时控制台输出如下错误信息:
[code="java"]log4j:WARN No appenders could be found for logger (org.springframework.core.CollectionFactory).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'constructorConfusion' defined in file [E:\test_workspace\spring\applicationContext.xml]: Unsatisfied dependency expressed through constructor argument with index 0 of type [java.lang.String]: Ambiguous constructor argument types - did you specify the correct bean references as constructor arguments?
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createArgumentArray(AbstractAutowireCapableBeanFactory.java:796)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:673)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:358)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:233)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:145)
at com.alpha.spring.ch4.ConstructorConfusion.main(ConstructorConfusion.java:17)
[/code]
哪位请告诉我哪里不对?