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>

 

 

测试结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值