文章目录
环境
pojo实体类:
package com.stdpei.pojo;
public class FirstProject {
private String str;
private int age;
public FirstProject() {
}
public FirstProject(String str, int age) {
this.str = str;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}
一、实现helloworld
1.创建并编辑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">
<bean id="FirstProject" class="com.stdpei.pojo.FirstProject">
<property name="str" value="hello world"/>
</bean>
</beans>
2.创建对象,并调用方法
在java中,实体类对象并不是new出来的,而是通过Spring的ApplicationContext 对象获取出来的。因为我们咋beans.xml中注册过实体类的bean,这与实体类的创建有很大的关系。
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
FirstProject firstProject = (FirstProject) context.getBean("FirstProject");
System.out.println(firstProject.getStr());
}
}
问题:
Hello对象是由谁来创建的?
- 对象是由Spring来创建的。
Hello的属性是由对来设置的?
- 属性是由Spring容器来设置的
上述的过程就是“控制反转”。
-
所谓的"控制"指的是,原来对于“对象的生杀大权”是由程序本身来控制的。但是是Spring中“对象的生杀大权”完全有Spring来控制。
-
所谓的"反转"指的是,原本对象的创建时由程序本身完成,但是现在是由Spring来完成。
上述的依赖注入,Spring是通过set方法来进行的。
IOC是一种编程思想,由原来的主动编程,到被动接受。
到此为止,我们就实现了第一个helloworld
二、IOC创建对象的方式
从(一)中我们可以发现并没有处理有参构造方法的实体类。下面我们进行详细的介绍。
1.通过参数类型进行创建
xml文件:
<bean id="FirstProject" class="com.stdpei.pojo.FirstProject">
<constructor-arg type="java.lang.String" value="hello world"/>
<constructor-arg type="int" value="18"/>
</bean>
对于基本数据类型(int、long、double、float…)参数的type为(int、long、double、float…)
存在的问题:当若多个参数的数据类型相同,就不太方便了
2.通过index进行创建
xml文件:
<bean id="FirstProject" class="com.stdpei.pojo.FirstProject">
<constructor-arg index="0" value="hello world"/>
<constructor-arg index="1" value="18"/>
</bean>
使用index的注意事项:index是从0开始的。
3.通过参数名进行创建【推荐】
<bean id="FirstProject" class="com.stdpei.pojo.FirstProject">
<constructor-arg name="str" value="hello world"/>
<constructor-arg name="age" value="18"/>
</bean>
这是一种最方便,也是最符合我们的认知的一种创建方式
4.特别的,当参数中含有其他实体类对象的时候,那么我们需要使用ref关键字
Student实体类构造函数:
Person实体类构造函数:
xml文件:
<bean id="student" class="com.stdpei.pojo.Student">
<property name="type" value="学生"/>
</bean>
<bean id="person" class="com.stdpei.pojo.Person">
<constructor-arg name="name" value="中国人"/>
<constructor-arg ref="student"/>
</bean>