Spring中的测试

Spring中的测试Spring中的测试

需要注意的是:

Spring中的测试

Spring中的测试

 

 

具体文件格式

Spring中的测试

Spring中的测试

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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd" >

<import resource="classpath:testworld/test-context.xml"></import>

</beans>

 

 

world类

package testworld;

 

public class world {

public world(){

System.out.println("所谓的焦虑就是书读得太少,而想得又太多");

}

public void sayhello(){

System.out.println("世界,你好");

}

}

 

 

test测试类

package testworld;

 

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.Resource;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

//SpringJUnit4ClassRunner.class为单元测试

@RunWith(SpringJUnit4ClassRunner.class)

//@ContextConfiguration:关联自己的测试文件,xml格式文件

////第一种设置方式

//@ContextConfiguration("classpath:testworld/world.xml")

//第二种设置方式

@ContextConfiguration

 

 

public class test {

@Test

public void test(){

//第一步获取资源文件classpath路径

Resource resource=new ClassPathResource("applicationContext.xml");

//第二步,根据资源文件创建spring容器

BeanFactory factory=new XmlBeanFactory(resource);

//创建对象

world wo=factory.getBean(world.class);

wo.sayhello();

}

//演示spring的测试

// @Autowired:自动把spring容器中的bean对象设置到wo,并且根据对象的类型来寻找到的

@Autowired

private world wo;

@Test

public void testbean(){

wo.sayhello();

}

}

 

 

test-context.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd" >

<bean id="hello" class="testworld.world"></bean>

</beans>

 

 

测试结果:

Spring中的测试

相关文章:

  • 2021-05-13
  • 2022-01-28
  • 2022-12-23
  • 2022-12-23
  • 2021-11-07
  • 2021-08-27
  • 2022-12-23
猜你喜欢
  • 2022-01-26
  • 2022-12-23
  • 2021-06-16
  • 2021-07-11
  • 2021-12-22
相关资源
相似解决方案