Loading

Spring笔记(二):第一个Spring程序

 

时间:2021/10/23

 

一.步骤

1.导入需要使用的依赖

这里我在pom.xml配置文件中导入了spring-webmvc和junit两个依赖

 1 <dependencies>
 2         <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
 3         <dependency>
 4             <groupId>org.springframework</groupId>
 5             <artifactId>spring-webmvc</artifactId>
 6             <version>5.3.12</version>
 7         </dependency>
 8 
 9         <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
10         <dependency>
11             <groupId>org.junit.jupiter</groupId>
12             <artifactId>junit-jupiter-api</artifactId>
13             <version>5.8.1</version>
14             <scope>test</scope>
15         </dependency>
16 
17     </dependencies>

 

2.编写实体类

 1 package bupt.machi.pojo;
 2 
 3 public class Hello {
 4 
 5     private String str;
 6 
 7     public String getStr() {
 8         return str;
 9     }
10 
11     public void setStr(String str) {
12         this.str = str;
13     }
14 
15     @Override
16     public String toString() {
17         return "Hello{" +
18                 "str='" + str + '\'' +
19                 '}';
20     }
21 }

 

3.在resources中编写Spring的配置文件(beans.xml)

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 5 
 6     <bean id="hello" class="bupt.machi.pojo.Hello">
 7 <!--   value:具体的值,基本数据类型
 8        ref:引用spring容器中创建好的对象
 9      -->
10         <property name="str" value="machi"/>
11     </bean>
12 </beans>

 

4.编写测试类

需要注意的是,这里的测试类路径不需要和pojo的路径一样,可以直接在Test文件夹下面(与mybatis中不同)

 1 import bupt.machi.pojo.Hello;
 2 import org.junit.jupiter.api.Test;
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 public class MyTest {
 7 
 8     @Test
 9     public void testHello(){
10         ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
11         Hello hello = (Hello) context.getBean("hello");
12         System.out.println(hello);
13     }
14 }

 

4.编写测试类

import bupt.machi.pojo.Hello;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {

    @Test
    public void testHello(){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello);
    }
}

 

 

二.总结

通过使用spring的IoC机制,我们可以彻底不用在程序中进行修改。要实现不同操作,只需要在xml配置文件中进行修改,所谓的IoC,就是:对象由spring来创建、管理和装配。

 

posted @ 2021-10-23 10:51    阅读(26)  评论(0编辑  收藏  举报