1、默认使用无参构造创建对象
Hello类
package com.qing.pojo;
public class Hello {
private String name;
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Hello{" +
"name='" + name + '\'' +
'}';
}
}
User类
package com.qing.pojo;
public class User {
String name;
public User(){
System.out.println("User无参构造执行");
}
public String setName(String name) {
this.name = name;
return name;
}
}
bean.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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="com.qing.pojo.Hello">
<property name="name" value="hello world"></property>
</bean>
<bean id="user" class="com.qing.pojo.User"/>
</beans>
测试,这里getBean只得到了hello对象,而User的无参构造也执行了,所以IOC容器创建对象默认是使用无参构造创建
package com.qing;
import com.qing.pojo.Hello;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloSpringTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
2、假设我们要使用有参构造创建对象,有三种方式
- 下标赋值
Hello类中添加一个有参构造
package com.qing.pojo;
public class Hello {
private String name;
public Hello(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Hello{" +
"name='" + name + '\'' +
'}';
}
}
给下标为0的参数赋值
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="com.qing.pojo.Hello">
<constructor-arg index="0" value="我是下标赋值"></constructor-arg>
</bean>
<bean id="user" class="com.qing.pojo.User">
</bean>
</beans>
测试,只执行了hello
package com.qing;
import com.qing.pojo.Hello;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloSpringTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
结果
- 类型
如果有两个String类型的参数,那该怎么办呢,所以不建议使用这种
- 参数名
不知道大家有没有想过,为什么没有去拿User对象,他的无参构造会调用
总结:在配置文件加载的时候,容器中管理的对象就已经初始化了