Spring Boot - MVC - RestTemplate:在哪里为 MVC 应用程序初始化

我将开发一个简单的 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:");


    }

}

我的问候控制器:


@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 类main成为 Application 类的功能并允许它由多个控制器共享,或每个控制器共享一个?完成此类任务的最佳实践是什么?


临摹微笑
浏览 217回答 2
2回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java