构造函数解析
构造函数解析示例,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的构造方法优先,然后才是默认构造方法