使用Spring注解方式注入properties文件内容,并配合Junit4+Spring做单元测试

先看看工作目录,然后再来讲解

1、建立config.properties,我的config.properties内容如下:


author_name=luolin
project_info=该项目主要是用于写一些demo



2、配置Spring配置文件,读取properties文件,并设置编码格式。大家从我的项目结构图中可以看到我用了两个Spring的配置文件,其实在spring-context.xml中没有配置其他内容,只是配置扫描com.eya.property这个包,大家可能会有疑问为何包的扫描不直接在spring-mvc.xml中配置成扫描com.eya就可以了。其实这是一个习惯问题,不同的东西做不同的事情,在 spring-mvc.xml中我只配置了去扫描com.eya.controller这个包。


<!-- 使用注解注入properties中的值 -->
	<bean id="setting"
		class="org.springframework.beans.factory.config.PropertiesFactoryBean">
		<property name="locations">
			<list>
				<value>classpath:config.properties</value>
			</list>
		</property>
		<!-- 设置编码格式 -->
		<property name="fileEncoding" value="UTF-8"></property>
	</bean>



3、编写和 config.properties文件中的值对应的ConfigProperty.java文件。加上注解@Comopnent("configProperty")将该类交给Spring容器管理,且指定该组件的名称为configProperty


这里说明一下,在使用@Value 注解的时候,其内部的格式是#{beanID[propertyKey]},这里的beanID是在第二步中配置PropertiesFactoryBean的时候指定的id值,propertyKey是和config.properties中的key对应。

/**
 * 
 */
package com.eya.property;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * config.properties文件映射类
 * @author luolin
 *
 * @version $id:ConfigProperty.java,v 0.1 2015年8月7日 下午2:10:44 luolin Exp $
 */
@Component("configProperty")
public class ConfigProperty {

    /** 作者名字 */
    @Value("#{setting[author_name]}")
    private String authorName;
    /** 项目信息 */
    @Value("#{setting[project_info]}")
    private String projectInfo;

    /**
     * @return the authorName
     */
    public String getAuthorName() {
        return authorName;
    }

    /**
     * @param authorName the authorName to set
     */
    public void setAuthorName(String authorName) {
        this.authorName = authorName;
    }

    /**
     * @return the projectInfo
     */
    public String getProjectInfo() {
        return projectInfo;
    }

    /**
     * @param projectInfo the projectInfo to set
     */
    public void setProjectInfo(String projectInfo) {
        this.projectInfo = projectInfo;
    }

}


4、编写单元测试,测试是否注入成功。这里用的是Junit4 + Spring注解的方式,当做是练习。


/**
 * 
 */
package com.eya.property;


import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * JUnit4 + Spring 注解进行单元测试,测试通过Spring注解获得Properties文件的值
 * @author luolin
 *
 * @version $id:ConfigPropertyTest.java,v 0.1 2015年8月7日 下午2:21:26 luolin Exp $
 */
@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations={"classpath:spring-mvc.xml","classpath:spring-context.xml"})
public class ConfigPropertyTest {

    @Resource(name = "configProperty")
    private ConfigProperty configProperty;
    
    /**
     * 测试Spring注解获取properties文件的值
     */
    @Test
    public void test() {
        System.out.println(configProperty.getAuthorName());
        System.out.println(configProperty.getProjectInfo());
    }

}


运行结果如图:



    期间出现了乱码的问题,由于我把config.properties的编码改成了UTF-8,开始没有在配置Spring文件的时候指定编码,所以乱码了,后来我看了下PropertiesFactoryBean的源代码,在它的父类中找到了设置编码的属性,设置成对应的编码就可以了。



转载于:https://my.oschina.net/simpleton/blog/489129

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用JUnit测试API接口,可以按照以下步骤进行: 1. 创建一个测试类,使用JUnitSpring Test等工具进行测试。 ```java @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class UserControllerTest { @Autowired private TestRestTemplate restTemplate; @Test public void testGetUserById() { ResponseEntity<User> response = restTemplate.getForEntity("/users/{id}", User.class, 1L); Assert.assertEquals(response.getStatusCode(), HttpStatus.OK); Assert.assertEquals(response.getBody().getId(), 1L); Assert.assertEquals(response.getBody().getName(), "Test"); Assert.assertEquals(response.getBody().getAge(), 18); } } ``` 在这个例子中,使用@RunWith和@SpringBootTest注解来配置测试环境,使用@Autowired注解注入TestRestTemplate对象,使用getForEntity方法来发送GET请求,使用Assert.assertEquals方法来进行测试。 2. 运行测试用例,查看测试结果。 在Eclipse、IntelliJ IDEA等IDE中,可以右键点击测试类并选择Run As JUnit Test来运行测试用例。测试结果将会在控制台中输出。 在这个例子中,假设UserController中有一个getUserById方法,用于获取ID为1的用户信息。在测试用例中,使用TestRestTemplate发送GET请求,并使用Assert.assertEquals方法来验证返回结果的正确性。注意,这个例子使用了@SpringBootTest注解中的RANDOM_PORT参数,表示随机选择一个可用的端口进行测试。如果需要指定端口号,可以使用@SpringBootTest注解中的properties参数,例如:@SpringBootTest(properties = {"server.port=8080"})。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值