2、使用有参构造函数(_springboot ioc 创建对象">
赞
踩
思考:为什么可以get到了bean?是不是Spring帮我们创建了?
上节课我们认识到,bean由Spring创建,管理和装配,体现了IOC的思想。
那IOC创建Bean有哪几种方式呢,我们去认识一下。
<bean id="user" class="com.blackcat.pojo.User">
<property name="name" value="张三"/>
</bean>
<bean id="user" class="com.blackcat.pojo.User">
<constructor-arg index="0" value="张三"/>
</bean>
<bean id="user" class="com.blackcat.pojo.User">
<constructor-arg type="java.lang.String" value="张三"/>//不推荐使用-
</bean>
<bean id="user" class="com.blackcat.pojo.User">
<constructor-arg name="name" value="张三"/>
</bean>
在配置文件加载的时候,对象就已经创建好了
package com.blackcat.pojo; public class User { public User() { System.out.println("User类的无参构造 执行了"); } public User(String name) { this.name = name; } private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "name='" + name + '\'' + '}'; } public void show(){ System.out.println("name = " + name); } }
package com.blackcat;
import com.blackcat.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) context.getBean("user");
user.show();
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。