1. 程式人生 > >[applicationContext.xml]: Initialization of bean failed;

[applicationContext.xml]: Initialization of bean failed;

錯誤程式碼如下


Error creating bean with name 'car' defined in class path resource [applicationContext.xml]: Initialization of bean failed;

nested exception is org.springframework.beans.TypeMismatchException:

Failed to convert property value of type 'java.lang.String' to required type 'double' for property 'price';

nested exception is java.lang.NumberFormatException: For input string: "Spring"


錯誤原因如下:

我是Spring的初學者

Car類裡面我定義了三個屬性,一個是String 一個是double 一個是int型別的

我一直以為value=100就是int、integer型別;其實不是;

無論是什麼型別的都是value="值"

<bean id="car" class="cn.com.day01.Car" >
<property name="name" value="Spring"></property>
<property name="price" value=90 ></property>
<property name="speed" value=100 ></property>
</bean>

由於上述的配置會導致整個xml檔案報錯,我就把value全部去掉了,然後在測試類裡面這樣寫

 //1.建立IOC容器
    ApplicationContext ioc=new  ClassPathXmlApplicationContext("applicationContext.xml");
    //2.獲取bean
    Car c=(Car) ioc.getBean("car");
    c.setName("寶馬");
    c.setPrice(1200);
    c.setSpeed(90);
    System.out.println(c.toString());

在bean配置檔案裡面,就已經給屬性初始化賦值了,

正確的應該是這樣的

<bean id="car" class="cn.com.day01.Car" >
<property name="name" value="Spring"></property>
<property name="price" value="90" ></property>
<property name="speed" value="100" ></property>
</bean>
//1.建立IOC容器
	ApplicationContext ioc=new  ClassPathXmlApplicationContext("applicationContext.xml");
	//2.獲取bean
	Car c=(Car) ioc.getBean("car");

	System.out.println(c.toString());