Spring Boot - MVC - RestTemplate:在哪里为 MVC 应用程序初始化 RestTemplate 以使用远程 RESTful 服务

ale*_*xtc 1 java spring spring-mvc resttemplate spring-boot

我将开发一个简单的 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 内容”来创建一个 Hello World 应用程序,并GreetingController举例说明。我想利用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:");

    }
}
Run Code Online (Sandbox Code Playgroud)

我的问候控制器:

@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";
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要如何以及在哪里初始化 RestTemplate,使 Singleton 类成为mainApplication 类的功能,并允许它由多个控制器或每个控制器共享一个?完成此类任务的最佳实践是什么?

Her*_*ers 5

看一下官方文档。实际上,您可以重用该模板并通过将其发布为主@Bean配置类(在您的情况下@SpringBootApplication)中来实例化它一次

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.build();
}
Run Code Online (Sandbox Code Playgroud)

GreetingController并通过将其自动装配为属性(或通过构造函数注入)将其注入:

@Autowired
private RestTemplate restTemplate;
Run Code Online (Sandbox Code Playgroud)

当然,如果您想自定义它,您也可以在控制器中本地RestTemplateBuilder注入并调用。build

private RestTemplate restTemplate;
public GreetingController(RestTemplateBuilder builder) {
    this.restTemplate = builder.build(); // modify it before building
}
Run Code Online (Sandbox Code Playgroud)