New Project
1.新建Module——spring-02-helloSpring
2. New package com.kuang.pojo
3. New Hello class
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. Create a new beans.xml under resource
<?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. Create a new test class
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());
}
}
Test Results:
6. Explanation of the HelloSpring creation process
使用Spring来创建对象,在Spring中这些都称为bean
类型 变量名 = new 类型();
Hello hello = new Hello();
bean = 对象 new Hello();
id = 变量名
class = new 的对象
property 相当于给对象中的属性设置一个值
-ref:引用Spring中创建好的对象
-value:具体的值,基本数据类型
- Who created the Hello object?
hello对象是Spring创建的
- How is the Hello object set up?
Hello对象是由Spring容器设置的
This process is called Inversion of Control
- control:
传统应用程序的对象是由程序本身控制创建的
使用了Spring后,由Spring来创建
- Invert:
程序本身不创建对象,而变成被动的接收对象
- Dependency injection:
利用set方法来进行注入