ioc对象创建方式
ioc对象创建方式:
注:无参构造是默认就有的(隐式)
1、Hello.java
package com.wang.pojo;
public class Hello {
private String str;
public Hello(){
System.out.println("隐式构造方法");
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
2、beans.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"> <!--使用spring创建对象,在spring这些都成为Bean--> <bean id="hello" class="com.wang.pojo.Hello"> <property name="str" value="Spring"> </property> </bean> </beans>
3、测试类MyTest.java
import com.wang.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
//获取spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象现在都在spring中的管理了,我们要使用们直接去里面取出来就可以
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
在调用toString方法之前,Hello对象已经通过无参构造初始化了!
通过有参构造方法来创建
1、User.java
public class User {
private String name;
public User(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("name="+ name );
}
}
2、beans.xml 有三种方式编写
<!-- 第一种根据index参数下标设置 --> <bean id="user" class="com.w.pojo.User"> <!-- index指构造方法 , 下标从0开始 --> <constructor-arg index="0" value="dog"/> </bean>
<!-- 第二种根据参数名字设置 --> <bean id="user" class="com.w.pojo.User"> <!-- name指参数名 --> <constructor-arg name="name" value="dog"/> </bean>
<!-- 第三种根据参数类型设置 --> <bean id="user" class="com.w.pojo.User"> <constructor-arg type="java.lang.String" value="dog"/> </bean>
3、测试
@Test
public void testT(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) context.getBean("user");
user.show();
}