學習使用springboot過程中發現寫在application.yml中的變量在測試類中讀取的時候總是出現null,網上找了一堆解決方案都不能解決問題。
配置文件application-default.yml內容如下
http:
host: www.baidu.com
port: 8888
環境條件:idea社區版
springboot:2.6.7
maven:3.8.1
JDK:1.8
現記錄解決方案如下:
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類確認加了必要的注解
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.測試類加上必要的注解
// 根據自己的來
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);
}
}
然后嘗試運行,完美解決問題
image.png
問題的關鍵是@ActiveProfiles這個注解,這個注解是在Spring單元測試加載ApplicationContext時指定profiles
@ActiveProfiles有以下參數:
profiles: 指定配置文件
resolver: 指定ActiveProfilesResolver,通過代碼指定配置文件
value: profiles的別名
inheritProfiles: 配置文件是否繼承父類,默認為true