- application.properties添加测试配置项
test.a=aaa
test.b=bbb
test.c=ccc
- 方式一、属性注入,相关注解:@Value
@Value("${test.a}")
String a;
@Test
public void 测试属性注入(){
Assert.assertEquals("aaa",a);
}
- 方式二、实体类映射,
相关注解:@Component、@ConfigurationProperties、@PropertySource,
备注1:prefix加上实体类属性名要对应配置文件的属性名,也可以同时使用@Value注入其他属性
备注2:@PropertySource(value="classpath:application.properties") 此注解不配置时默认application.properties,可省略
package com.example.demo.domain;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;@Component
@ConfigurationProperties(prefix="test")
@PropertySource(value="classpath:application.properties")
public class TestSettings {
private String a;
private String b;
private String c;
@Value("${test.c}")
private String d;public String getA() {
return a;
}public void setA(String a) {
this.a = a;
}public String getB() {
return b;
}public void setB(String b) {
this.b = b;
}public String getC() {
return c;
}public void setC(String c) {
this.c = c;
}public String getD() {
return d;
}public void setD(String d) {
this.d = d;
}@Override
public String toString() {
return "TestSettings [a=" + a + ", b=" + b + ", c=" + c + ", d=" + d + "]";
}}
- 测试类
package com.example.demo;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import com.example.demo.domain.TestSettings;
@RunWith(SpringRunner.class)
@SpringBootTest
public class PropertiesTest {
@Value("${test.a}")
private String a;
@Test
public void 测试属性注入(){
Assert.assertEquals("aaa",a);
}
@Autowired
private TestSettings testSettings;
@Test
public void 测试对象注入(){
System.out.println(testSettings.toString());
Assert.assertEquals("aaa",testSettings.getA());
}}