Java 以编程方式检索SpringFeignClient调用的URL
我试图找到一种方法来检索当前由Spring应用程序中的假客户端方法接口映射的URL,但我还没有找到解决方案。以下代码起作用: pom.xmlJava 以编程方式检索SpringFeignClient调用的URL,java,spring,spring-boot,spring-cloud-feign,Java,Spring,Spring Boot,Spring Cloud Feign,我试图找到一种方法来检索当前由Spring应用程序中的假客户端方法接口映射的URL,但我还没有找到解决方案。以下代码起作用: pom.xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>2.1.1.RELEASE&
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
ApiClient.class
package com.example.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name = "json-placeholder", url = "${api.url}")
public interface ApiClient {
@GetMapping(value = "/posts", consumes = "application/json")
ResponseEntity<String> getPosts();
}
我试图直接从注释中编写这个URL,但它似乎不起作用。有谁能给我一个选择吗?多谢各位
- 编辑注释-
关于这个更新的场景有什么想法吗?我需要的是这个URL实际上是由假客户端调用的。我知道所有提供的解决方案实际上都是解决办法。更清楚地说,指定的行应该打印
”https://jsonplaceholder.typicode.com/posts
。一个简单的解决方法是将URL设置为ApiClient的公共静态最终字符串字段,例如公共静态最终字符串URL=https://jsonplaceholder.typicode.com"
。您的注释可以使用url=ApiClient.url
引用它。你可以在任何地方引用这个变量。对不起,我可以这样做。请看我的最新声明。URL值需要作为application.yml属性注入,并且会因环境而异。更清楚地说,指定的行应该打印“https://jsonplaceholder.typicode.com/posts“
。一个简单的解决方法是将URL设置为ApiClient的公共静态最终字符串字段,例如,公共静态最终字符串URL="https://jsonplaceholder.typicode.com“
。您的批注可以使用url=ApiClient.url
引用它。然后,您可以在任何地方引用此变量。抱歉,但我可以这样做。请参阅我的更新语句。url值需要作为application.yml属性注入,并且会因环境而异。
package com.example.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name = "json-placeholder", url = "${api.url}")
public interface ApiClient {
@GetMapping(value = "/posts", consumes = "application/json")
ResponseEntity<String> getPosts();
}
package com.example.feign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import javax.annotation.PostConstruct;
@EnableFeignClients
@SpringBootApplication
public class FeignApplication {
public static void main(String[] args) {
SpringApplication.run(FeignApplication.class, args);
}
@Autowired
private ApiClient apiClient;
@PostConstruct
public void test() {
// this works
System.out.println(apiClient.getPosts().getBody());
// apiClient. ... getPosts request URL
}
}