spring屬性注入必須有預設構造方法
阿新 • • 發佈:2018-12-30
最基本的物件建立方式,只需要有一個無參建構函式(類中沒有寫任何的建構函式,預設就是有一個建構函式,如果寫了任何一個建構函式,預設的無參建構函式就不會自動建立哦!!)和欄位的setter方法。
Person類:
package com.mc.base.learn.spring.bean;
public class Person {
private String name;
private Integer id;
public String getName() {
return name;
}
public void setName (String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public String toString() {
return "Person [name=" + name + ", id=" + id + "]";
}
}
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 class="com.mc.base.learn.spring.bean.Person" id="person" >
<property name="name" value="LiuChunfu"></property>
<property name="id" value="125"></property>
</bean>
</beans>
其本質為:
SpringContext利用無參的建構函式建立一個物件,然後利用setter方法賦值。所以如果無參建構函式不存在,Spring上下文建立物件的時候便會報錯。
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'person' defined in class path resource [applicationContext.xml]: Instantiation of bean failed;
nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mc.base.learn.spring.bean.Person]: No default constructor found;
nested exception is java.lang.NoSuchMethodException: com.mc.base.learn.spring.bean.Person.<init>()
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1105)
。。。。。