3.第一个Spring程序
附文档:https://docs.spring.io/spring/docs/5.2.3.RELEASE/spring-framework-reference/core.html#spring-core
编写hello实体类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20package pojo;
public class Hello {
private String str;
public Hello() {
}
public Hello(String str) {
this.str = str;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}Dao层接口
1
2
3
4
5package dao;
public interface UserDao {
void getUser();
}资源文件夹引入Spring配置文件(beans.xml),并且编写beans标签初始化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<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-->
<!-- id=变量名 class=new的对象 -->
<bean id="hello" class="pojo.Hello">
<property name="str" value="Spring"></property>
<!--property给对象设置初始值-->
</bean>
</beans>测试类
1
2
3
4
5
6
7
8
9
10
public void test1(){
//获取Spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象都在Spring中管理了,我们要使用,直接拿出来用就可以了
Hello hello =(Hello) context.getBean("hello");
System.out.println(hello.getStr());
}
思考
对象是谁创建的?
hello对象是Spring创建的
hello对象的属性是怎么设置的?
hello对象的属性是由Spring容器设置的
这个过程就叫控制反转
控制:谁来控制对象的创建,传统应用程序的对象是程序本身创建的,使用spring后,对象是由spring管理的
反转:程序本身不创建对象,而是被动的接收对象
依赖注入:就是利用set方法注入的
IOC是一种编程思想,由主动的变成被动的接受
OK,到了现在,我们再也不用在程序中改动了,要实现不同的操作,只需要在xml中进行修改,所谓的IOC一句话搞定:对象由Spring来创建、管理、装配!