错误代码如下
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());