構造函數解析
構造函數解析示例,code 如下。
定義實體類:
package com.gientech.constructor;
public class Person {
private String name;
private int id;
private int age;
private String sex;
public Person() {
}
public Person(String name) {
this.name = name;
}
public Person(String name, String sex) {
this.name = name;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
新增配置文件
<?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="person" class="com.gientech.constructor.Person">
<property name="name" value="lisi"></property>
<property name="sex" value="man"></property>
<!-- <constructor-arg name="sex" value="man"></constructor-arg>-->
<!-- <constructor-arg name="name" value="zhangsan"></constructor-arg>-->
</bean>
</beans>
新增啓動類
package com.gientech.constructor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ConstructorTest {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("constructortest.xml");
Person bean = ac.getBean(Person.class);
System.out.println(bean.getName());
}
}
構造函數解析執行順序如下:
doCreateBean -> createBeanInstance -> autowireConstructor -> ConstructorResolver.autowireConstructor
determineCandidateConstructors 方法作用是獲取構造器,有4種場景
- 如果有多個Autowired,required爲true,不管有沒有默認構造方法,會報異常
- 如果只有一個Autowired,required爲false,沒有默認構造方法,會報警告
- 如果沒有Autowired註解,定義了兩個及以上有參數的構造方法,沒有無參構造方法,且不是通過xml配置文件進行加載,使用@Component進行加載就會報錯
- 其他情況都可以,但是以有Autowired的構造方法優先,然後纔是默認構造方法