Java Spring Boot@Value未填充..为什么?

Java Spring Boot@Value未填充..为什么?,java,spring-boot,testing,properties,null,Java,Spring Boot,Testing,Properties,Null,我正在尝试使用@value从Spring Boot中的application.properties获取一个值,但无论我做什么,它始终为null 我在我的HTTPClient测试类中这样做。我尝试过使用环境变量、propertySource、PostConstruct、getter和setter,以及我在网上能找到的任何东西,但它似乎一点也没有普及。。。我的测试类在src/test/java中,application.properties在src/test/resources中。我的src/mai

我正在尝试使用@value从Spring Boot中的application.properties获取一个值,但无论我做什么,它始终为null

我在我的HTTPClient测试类中这样做。我尝试过使用环境变量、propertySource、PostConstruct、getter和setter,以及我在网上能找到的任何东西,但它似乎一点也没有普及。。。我的测试类在src/test/java中,application.properties在src/test/resources中。我的src/main/java中也有一个application.properties,但它位于一个完全不同的文件夹中,因此不应该影响它

这是我的密码:

import static org.junit.Assert.*;
import java.io.IOException;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ConfigurableApplicationContext;
import com.google.gson.Gson;
import com.nulogix.billing.configuration.EndPointTestConfiguration;
import com.nulogix.billing.mockserver.MockServerApp;

@SpringBootTest(classes = EndPointTestConfiguration.class)
public class HttpClientTest {
    @Value("${billing.engine.address}")
    private String billingEngineAddress;
    @Value("${billing.engine.port}")
    private String billingEnginePort;


    @PostConstruct
    private void customInit() {
        System.out.print(billingEngineAddress);
        System.out.print(billingEnginePort);

    }

    public static final String request_bad  = "ncs|56-2629193|1972-03-28|20190218|77067|6208|3209440|self|";
    public static final String request_good = "ncs|56-2629193|1972-03-28|20190218|77067|6208|3209440|self|-123|-123|-123|0.0|0.0|0.0|0.0|0.0|0.0|0.0";



    @Test
    public void test_bad() throws ClientProtocolException, IOException {
        // missing parameter

        String result = Request.Post("http://" + billingEngineAddress + ":" + billingEnginePort)
                .connectTimeout(2000)
                .socketTimeout(2000)
                .bodyString(request_bad, ContentType.TEXT_PLAIN)
                .execute().returnContent().asString();

        Map<?, ?> resultJsonObj = new Gson().fromJson(result, Map.class);

        // ensure the key exists
        assertEquals(resultJsonObj.containsKey("status"), true);
        assertEquals(resultJsonObj.containsKey("errorMessage"), true);

        // validate values
        Boolean status = (Boolean) resultJsonObj.get("status");
        assertEquals(status, false);
        String errorMessage = (String) resultJsonObj.get("errorMessage");
        assertEquals(errorMessage.contains("Payload has incorrect amount of parts"), true);

    }


    @Test
    public void test_good() throws ClientProtocolException, IOException {
        String result = Request.Post("http://" + billingEngineAddress + ":" + billingEnginePort)
                .connectTimeout(2000)
                .socketTimeout(2000)
                .bodyString(request_good, ContentType.TEXT_PLAIN)
                .execute().returnContent().asString();

        Map<?, ?> resultJsonObj = new Gson().fromJson(result, Map.class);

        // ensure the key exists
        assertEquals(resultJsonObj.containsKey("status"), true);
        assertEquals(resultJsonObj.containsKey("errorMessage"), false);
        assertEquals(resultJsonObj.containsKey("HasCopay"), true);
        assertEquals(resultJsonObj.containsKey("CopayAmount"), true);
        assertEquals(resultJsonObj.containsKey("HasCoinsurance"), true);
        assertEquals(resultJsonObj.containsKey("CoinsuranceAmount"), true);
        assertEquals(resultJsonObj.containsKey("version"), true);

        // validate values
        Boolean status = (Boolean) resultJsonObj.get("status");
        assertEquals(status, true);
        String version = (String) resultJsonObj.get("version");
        assertEquals(version, "0.97");

    }

}

您需要将application.properties移动到
src/test/resource
文件夹。对于测试,弹簧从该路径加载应用程序属性。

您需要将application.properties移动到
src/test/resource
文件夹。对于测试,请从此路径选择弹簧载荷应用程序属性。

您可以执行以下操作:

@RunWith(SpringRunner.class)
@SpringBootTest(classes={Application.class})
public class HttpClientTest {
.............
.................
}

您可以执行以下操作:

@RunWith(SpringRunner.class)
@SpringBootTest(classes={Application.class})
public class HttpClientTest {
.............
.................
}

因此,解决我的问题的方法是将application.properties从我的main复制到我的测试/资源。然后,我使用@PropertySource将值更改为test.properties,将其与main中的application.properties分开。我在端点配置中创建了一个值bean,然后将其自动连接到httpclient测试类中

我还在SpringBootTest注释中添加了web环境,以使用test.properties中定义的端口,并使用端点配置类和主应用程序类运行测试。这导致@value字符串被填充且不为null

@Configuration
public class EndPointTestConfiguration {

    @Value("${billing.engine.address}")
    private String mockServerIP;
    @Value("${billing.engine.port}")
    private String mockServerPort;

    @Bean
    public String mockAddress() {
        String mockServerAddress = "http://" + mockServerIP + ":" + mockServerPort;
        return mockServerAddress;

    }



    @Bean
    public GetVersionEndPoint getVersionEndPoint() {
        return new GetVersionEndPoint();
    }

    @Bean
    public AnalyzeEndPoint analyzeEndPoint() throws JAXBException {
        return new AnalyzeEndPoint();
    }

    @Bean
    public PredictionEngineService predictionEngineService() {
        return new PredictionEngineService();
    }

    @Bean
    public String studyDetailDemo() throws IOException {
        File file = ResourceUtils.getFile("src/test/resources/study-details-demo.txt");
        String content = new String(Files.readAllBytes(file.toPath()));
        return content;
    }

    @Bean
    public String studyDetailSampleNormal() throws IOException {
        File file = ResourceUtils.getFile("src/test/resources/study-details-normal.txt");
        String content = new String(Files.readAllBytes(file.toPath()));
        return content;
    }

    @Bean
    public String studyDetailSampleCms() throws IOException {
        File file = ResourceUtils.getFile("src/test/resources/study-details-cms.txt");
        String content = new String(Files.readAllBytes(file.toPath()));
        return content;
    }

}
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=SpringBootTest.webEnvironment.DEFINED_PORT,class={EndPointTestConfiguration.class,MockServerApp.class
})
@PropertySource(值={“classpath:test.properties”},ignoreResourceNotFound=true)
公共类HttpClientTest{
@自动连线
私有字符串地址;
公共静态最终字符串请求_bad=“ncs | 56-2629193 | 1972-03-28 | 20190218 | 77067 | 6208 | 3209440 | self |”;
公共静态最终字符串请求_good=“ncs | 56-2629193 | 1972-03-28 | 20190218 | 77067 | 6208 | 3209440 | self |-123 |-123 |-123 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0”;
@试验
public void test_bad()抛出ClientProtocolException,IOException{
//缺失参数
字符串结果=Request.Post(mockAddress)
.2000年
.socketTimeout(2000年)
.bodyString(请求错误,内容类型为.TEXT\u纯)
.execute().returnContent().asString();
Map resultJsonObj=new Gson().fromJson(result,Map.class);
//确保密钥存在
assertEquals(resultJsonObj.containsKey(“状态”),true);
assertEquals(resultJsonObj.containsKey(“错误消息”),true);
//验证值
布尔状态=(布尔)resultJsonObj.get(“状态”);
资产质量(状态,错误);
String errorMessage=(String)resultJsonObj.get(“errorMessage”);
assertEquals(errorMessage.contains(“有效负载的部件数量不正确”)、true;
}
@试验
public void test_good()抛出ClientProtocolException,IOException{
字符串结果=Request.Post(mockAddress)
.2000年
.socketTimeout(2000年)
.bodyString(请求良好,ContentType.TEXT普通)
.execute().returnContent().asString();
Map resultJsonObj=new Gson().fromJson(result,Map.class);
//确保密钥存在
assertEquals(resultJsonObj.containsKey(“状态”),true);
assertEquals(resultJsonObj.containsKey(“errorMessage”),false;
资产质量(resultJsonObj.containsKey(“HasCopay”),真实);
assertEquals(resultJsonObj.containsKey(“CopayAmount”),true);
资产质量(resultJsonObj.containsKey(“Hascoinconsurance”),真实);
资产质量(结果JSONOBJ.containsKey(“共同保险金额”),真实);
assertEquals(resultJsonObj.containsKey(“版本”),true);
//验证值
布尔状态=(布尔)resultJsonObj.get(“状态”);
assertEquals(状态,true);
字符串版本=(字符串)resultJsonObj.get(“版本”);
资产质量(0.97版);
}
}

因此,解决我的问题的方法是将application.properties从我的main复制到我的测试/资源。然后,我使用@PropertySource将值更改为test.properties,将其与main中的application.properties分开。我在端点配置中创建了一个值bean,然后将其自动连接到httpclient测试类中

我还在SpringBootTest注释中添加了web环境,以使用test.properties中定义的端口,并使用端点配置类和主应用程序类运行测试。这导致@value字符串被填充且不为null

@Configuration
public class EndPointTestConfiguration {

    @Value("${billing.engine.address}")
    private String mockServerIP;
    @Value("${billing.engine.port}")
    private String mockServerPort;

    @Bean
    public String mockAddress() {
        String mockServerAddress = "http://" + mockServerIP + ":" + mockServerPort;
        return mockServerAddress;

    }



    @Bean
    public GetVersionEndPoint getVersionEndPoint() {
        return new GetVersionEndPoint();
    }

    @Bean
    public AnalyzeEndPoint analyzeEndPoint() throws JAXBException {
        return new AnalyzeEndPoint();
    }

    @Bean
    public PredictionEngineService predictionEngineService() {
        return new PredictionEngineService();
    }

    @Bean
    public String studyDetailDemo() throws IOException {
        File file = ResourceUtils.getFile("src/test/resources/study-details-demo.txt");
        String content = new String(Files.readAllBytes(file.toPath()));
        return content;
    }

    @Bean
    public String studyDetailSampleNormal() throws IOException {
        File file = ResourceUtils.getFile("src/test/resources/study-details-normal.txt");
        String content = new String(Files.readAllBytes(file.toPath()));
        return content;
    }

    @Bean
    public String studyDetailSampleCms() throws IOException {
        File file = ResourceUtils.getFile("src/test/resources/study-details-cms.txt");
        String content = new String(Files.readAllBytes(file.toPath()));
        return content;
    }

}
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=SpringBootTest.webEnvironment.DEFINED_PORT,class={EndPointTestConfiguration.class,MockServerApp.class
})
@PropertySource(值={“classpath:test.properties”},ignoreResourceNotFound=true)
公共类HttpClientTest{
@自动连线
私有字符串地址;
公共静态最终字符串请求_bad=“ncs | 56-2629193 | 1972-03-28 | 20190218 | 77067 | 6208 | 3209440 | self |”;
公共静态最终字符串请求_good=“ncs | 56-2629193 | 1972-03-28 | 20190218 | 77067 | 6208 | 3209440 | self |-123 |-123 |-123 | 0.0 | 0.0 | 0.0 | 0.0 | 0.0”;
@试验
public void test_bad()抛出ClientProtocolException,IOException{
//缺失参数
字符串结果=Request.Post(mockAddress)
.2000年
.socketTimeout(2000年)
.bodyString(请求错误,内容类型为.TEXT\u纯)
.execute().returnContent().asString();
Map resultJsonObj=new Gson().fromJson(result,Map.class);
//确保密钥存在
assertEquals(resultJsonObj.containsKey(“状态”),true);
A.