[英]Spring Boot - MVC - RestTemplate: Where to initialize a RestTemplate for a MVC application to consume remote RESTful services
我將開發一個簡單的Spring MVC Web應用程序,它將使用Heroku上的遠程RESTful服務。
我希望MVC Web應用程序根據控制器調用REST服務。 例如
localhost:8080/items
以調用http://{REMOTE_SERVER}/api/items
localhost:8080/users
呼叫http://{REMOTE_SERVER}/api/users
等等等
我按照Spring的官方Spring Boot文檔“使用Spring MVC服務Web內容”創建了一個帶有GreetingController
的Hello World應用程序作為示例。 我想利用Spring的RestTemplate調用REST服務。
我的應用程序類:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
System.out.println("Let's inspect the beans provided by Spring Boot:");
}
}
我的GreetingController:
@Controller
public class GreetingController {
@GetMapping("/greeting")
public String greeting(@RequestParam(name = "name", required = false, defaultValue = "World") String name,
Model model) {
model.addAttribute("name", name);
return "greeting";
}
}
我需要如何以及在何處初始化RestTemplate,使Singleton類成為Application類的main
功能,並允許它由多個控制器共享,或者每個控制器共享一個? 完成這項任務的最佳實踐是什么?
看一下官方文檔 。 實際上,您可以通過在主配置類@Bean
其作為@Bean
發布(在您的情況下為@SpringBootApplication
)來重用模板並將其實例化一次。
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
並通過自動將其作為屬性(或通過構造函數注入)將其注入到GreetingController
:
@Autowired
private RestTemplate restTemplate;
當然,如果您要自定義它,也可以注入RestTemplateBuilder
並在控制器中本地調用build
。
private RestTemplate restTemplate;
public GreetingController(RestTemplateBuilder builder) {
this.restTemplate = builder.build(); // modify it before building
}
這很簡單。
您只需要創建一個new
RestTemplate並使用它即可。 更好的方法是讓應用程序級別的RestTemplate由spring上下文管理。 將以下工廠方法添加到您的@Configuration文件中
@Bean
public RestTemplate myRestTemplate() {
return new RestTemplate();
}
使用它:
public MyClass{
@Autowired
RestTemplate myRestTemplate;
public void myMethod(){
// use rest template
}
}
單例或每主機一個
從Spring Docs
RestTemplate
RestTemplate是用於客戶端HTTP訪問的中央Spring類。 從概念上講,它與JdbcTemplate,JmsTemplate以及在Spring Framework和其他項目組合項目中找到的各種其他模板非常相似。 例如,這意味着RestTemplate一旦構建便是線程安全的,並且您可以使用回調來自定義其操作。
因此,您可以安全地創建RestTemplate以便與多個線程共享,並與不同的主機同時調用REST調用。
參考: https : //spring.io/blog/2009/03/27/rest-in-spring-3-resttemplate
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.