學(xué)習(xí)使用springboot過程中發(fā)現(xiàn)寫在application.yml中的變量在測試類中讀取的時(shí)候總是出現(xiàn)null,網(wǎng)上找了一堆解決方案都不能解決問題。
配置文件application-default.yml內(nèi)容如下
http:
host: www.baidu.com
port: 8888
環(huán)境條件:idea社區(qū)版
springboot:2.6.7
maven:3.8.1
JDK:1.8
現(xiàn)記錄解決方案如下:
1.pom.xml確保引入必要的依賴
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 自定義配置需要的依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
2.config類確認(rèn)加了必要的注解
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "http")
@Getter
@Setter
@ToString
public class HTTPConfig {
private String host;
private String port;
}
3.測試類加上必要的注解
// 根據(jù)自己的來
import com.xxx.datatest.config.HTTPConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes={DatatestApplication.class})
@ActiveProfiles("uat")
public class YmlTests {
@Autowired
private HTTPConfig httpConfig;
@Test
public void contextLoads() {
System.out.println(httpConfig);
}
}
然后嘗試運(yùn)行仗哨,完美解決問題
問題的關(guān)鍵是@ActiveProfiles這個(gè)注解,這個(gè)注解是在Spring單元測試加載ApplicationContext時(shí)指定profiles
@ActiveProfiles有以下參數(shù):
profiles: 指定配置文件
resolver: 指定ActiveProfilesResolver计济,通過代碼指定配置文件
value: profiles的別名
inheritProfiles: 配置文件是否繼承父類刽宪,默認(rèn)為true