1.导包
创建一个空的maven项目
在pom.xml里面添加依赖:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
</dependencies>
2.在pojo下自定义实体类
package com.zhou.pojo;
public class HelloStr {
private String name;
public HelloStr() {
}
public HelloStr(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "HelloStr{" +
"name='" + name + '\'' +
'}';
}
}
3.在resources目录下创建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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
使用spring来创建对象,对象在spring中成为bean
class内容等价于 new的对象
id等价于新建对象的变量名。 对象的属性由property设置
-->
<bean id="Hello" class="com.zhou.pojo.HelloStr" >
<property name="name" value="spring容器 入门"></property>
</bean>
</beans>
4.在test/java目录下编写测试程序
import com.zhou.pojo.HelloStr;
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容器中
HelloStr helloStr =(HelloStr) context.getBean("Hello");
System.out.println(helloStr.toString());
}
}
测试成功输出:HelloStr{name=‘spring容器 入门’}