导入依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
</dependencies>
注:新建一个Maven项目,然后删除src,删除后在项目中创建新的子工程,在子工程中实现下文代码。上图依赖只需导入父工程中即可,子工程中无需再次导入。
一、使用无参构造创建对象(ioc默认创建对象方式)
例如:
Hello类:
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "com.wei.pojo.Hello{" +
"str='" + str + '\'' +
'}';
}
}
配置文件:
<bean>中的id相当于(类名 + 变量名 = new 类名())中的变量名,class相当于new 类名()。
"com.wei.pojo.Hello"是上图Hello类的地址(包名+类名)。
<bean id="hello" class="com.wei.pojo.Hello">
<property name="str" value="String"/>
</bean>
二、使用有参构造创建对象(三种方法)
public class Hello {
private String str;
//有参构造
public Hello(String str) {
this.str = str;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "com.wei.pojo.Hello{" +
"str='" + str + '\'' +
'}';
}
}
使用有参构造不能用无参构造的方法去创建对象
方法一、
使用index属性显式指定构造函数参数的索引。例如:
<bean id="hello" class="com.wei.pojo.Hello">
<constructor-arg index="0" value="HelloSpring"/>
</bean>
方法二、
在前面的场景中,如果使用type属性显式地指定构造函数参数的类型,容器可以使用与简单类型匹配的类型。例如:
<bean id="hello" class="com.wei.pojo.Hello">
<constructor-arg type="java.lang.String" value="HelloSpring"/>
//如果是整型 type = "int"
</bean>
(假如我们的有参构造的参数大于一(相同类型),这种方法不能为各个参数赋值,局限性比较大,不推荐使用)
方法三、
也可以使用构造函数的参数名来消除值歧义:
<bean id="hello" class="com.wei.pojo.Hello">
<constructor-arg name="str" value="HelloSpring"/>
</bean>
(这种方式推荐使用!!!)
三、
测试类
public static void main(String[] args) {
//获取Spring的上下文对象!
ApplicationContext context = new ClassPathXmlApplicationContext("applicationConText.xml");
//强制转换成Hello的对象
Hello hello =(Hello) context.getBean("hello");
System.out.println(hello.toString());
}
注:以上只是个人见解,如有不足,还请各位大佬指教~~~~