新建项目
1.新建Module——spring-02-helloSpring
2.新建包com.kuang.pojo
3.新建Hello类
package com.kuang.pojo;
public class Hello {
private String str;
public String getStr(){
return str;
}
public void setStr(String str){
this.str=str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
4. 在resource下新建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.kuang.pojo.Hello">
<property name="str" value="Spring" />
</bean>
</beans>
5.新建测试类
import com.kuang.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());
}
}
测试结果:
6.对HelloSpring创建过程的解释
使用Spring来创建对象,在Spring中这些都称为bean
类型 变量名 = new 类型();
Hello hello = new Hello();
bean = 对象 new Hello();
id = 变量名
class = new 的对象
property 相当于给对象中的属性设置一个值
-ref:引用Spring中创建好的对象
-value:具体的值,基本数据类型
- Hello对象时谁创建的?
hello对象是Spring创建的
- Hello对象是怎么设置的?
Hello对象是由Spring容器设置的
这个过程叫控制反转
- 控制:
传统应用程序的对象是由程序本身控制创建的
使用了Spring后,由Spring来创建
- 反转:
程序本身不创建对象,而变成被动的接收对象
- 依赖注入:
利用set方法来进行注入