时间:2021/10/23
这里我在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>
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 }
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 }
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来创建、管理和装配。