我正在Spring Boot 1.5.6中编写Rest Client for 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)
你能指导我吗?
答案 0 :(得分:1)
问题是变量的static
性质。春天的@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;
}
}