Spring学习笔记——第二部分 Spring入门程序
1. 编写实体类Hello.java
package com.zhang.pojo;
public class Hello {
private String str;
public void setStr(String str) {
this.str = str;
}
public String getStr() {
return str;
}
@Override
public String toString(){
return "Hello{" +
"str='" + str +"\'" +
"}";
}
}
2. 编写配置文件applicationContext.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="hello" class="com.zhang.pojo.Hello">
<property name="str" value="Spring"/>
</bean>
</beans>
- 文件中,第七到第九行代码表示:在Spring容器中创建一个id为hello的bean实例,其中class属性用于指示需要实例化的类,即我们第一步写的Hello类。
- 同时使用property标签,对Hello类中的str属性进行赋值,值(value)为Spring。
- 在Spring中,我们一般都将配置文件命名为applicationContext.xml,或者beans.xml
3. 编写测试类
- 初始化Spring容器,加载配置文件
- 通过容器获取Hello实例
- 输出
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello);
}
4. 测试结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3553aa8b63cbb916f60193b692d1cc9d.png)
- 观察上图,我们发现,控制台已经正确输出结果,而我们并没有通过new关键字来创建Hello的实例化对象,而是通过Spring容器来获取的实现类对象,这就是Spring IoC容器的工作机制。