gpt4 book ai didi

java - Spring Boot 客户端应用程序中未加载属性

转载 作者:行者123 更新时间:2023-12-02 12:14:35 25 4
gpt4 key购买 nike

我正在 Spring boot 1.5.6 中为 Rest 服务编写 Rest 客户端。下面是主要类:

@SpringBootApplication
public class MyApp {

public static void main(String[] args) {
SpringApplication.run(My.class, args);
MyClient.saveAction(...parameters here....);
}

}

下面是调用休息服务的 MyClient 类:

@Component
public class MyClient {

@Value("${my.rest.uri}")
private static String MyUri;

/**
* Log user actions.
*/
public static void saveAction(..parameters..) {
RestTemplate restTemplate = new RestTemplate();
String queryParameters = String.format("...parameters...");
restTemplate.postForObject(MyUri + "?" + queryParameters,null, ResponseEntity.class);
}
}

application.properties

spring.main.web-environment=false
spring.main.banner_mode=off
my.rest.uri=http://localhost:9082/test/api/v1/testapi

问题是 my.rest.uri 属性未从 application.properties 文件加载。结果,我收到以下错误:

Exception in thread "main" java.lang.IllegalArgumentException: URI is not absolute
at java.net.URI.toURL(URI.java:1088)
at org.springframework.http.client.SimpleClientHttpRequestFactory.createRequest(SimpleClientHttpRequestFactory.java:141)
at org.springframework.http.client.support.HttpAccessor.createRequest(HttpAccessor.java:85)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:648)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:380)
at com.my.client.service.myClient.saveAction(MyClient.java:40)

你能指导我吗?

最佳答案

问题在于变量的静态性质。 Spring 的 @Value 在那里不起作用。因此,要么删除静态方法和变量(如果您使用单例作用域 bean,则建议这样做),要么使用非静态初始化程序。以下是选项:

使用非静态方法

@Component
public class MyClient {

@Value("${my.rest.uri}")
private String MyUri;

/**
* Log user actions.
*/
public void saveAction(..parameters..) {
RestTemplate restTemplate = new RestTemplate();
String queryParameters = String.format("...parameters...");
restTemplate.postForObject(MyUri + "?" + queryParameters,null, ResponseEntity.class);
}
}

非静态初始化器

@Component
public class MyClient {


private static String MyUri;

/**
* Log user actions.
*/
public static void saveAction(..parameters..) {
RestTemplate restTemplate = new RestTemplate();
String queryParameters = String.format("...parameters...");
restTemplate.postForObject(MyUri + "?" + queryParameters,null, ResponseEntity.class);
}


public void setMyUri( @Value("${my.rest.uri}") String uri) {
MyUri = uri;
}


}

关于java - Spring Boot 客户端应用程序中未加载属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46279878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com