首页 > 解决方案 > Sprint 启动 - 自动配置为在启动时调用 REST 服务

问题描述

我需要在 spring-boot 启动时为服务调用创建自动配置。

即,在 spring-boot 启动期间,必须调用以下服务。

@PostMapping(path = "/addProduct", produces = "application/json", consumes = "application/json")
    public @ResponseBody String addProduct(@RequestBody String productStr) {
    ..<My code>..
}

添加产品需要如下输入:

{
  "product":"test",
  "price":"10"
}

这将在内部调用数据库服务。

在启动期间,应将控制台中提供的 json 输入提供给该服务。

我不知道如何实现这一目标。验证了几个 Spring 文档。但那些不符合要求。

请帮助解释一种方法或提供正确的文档来实现这一目标。

标签: springspring-boot

解决方案


一种方法是像这样实现 ApplicationRunner:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class ApplicationInitializer implements ApplicationRunner {

    private ProductController productController;

    public ApplicationInitializer(ProductController productController) {
        this.productController = productController;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        String productArg = args.getOptionValues("product").get(0); // Assume that you will have only one product argument
        ObjectMapper mapper = new ObjectMapper();
        Product product = mapper.readValue(productArg, Product.class);
        String response = productController.add(product);

        System.out.println(response);
    }
}

run 方法将在启动时调用,并在命令行中传递参数,如下所示:java -jar yourApp.jar --product="{\"name\":\"test\", \"price\":\"15\"}"

你需要一个类来将 json 映射到这样的对象:

public class Product {

    private String name;

    private int price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }
}

如果需要,您还可以使用 RestTemplate(或 WebClient)调用您的控制器:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class ApplicationInitializer implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        String productArg = args.getOptionValues("product").get(0); // Assume that you will have only one product argument
        ObjectMapper mapper = new ObjectMapper();
        Product product = mapper.readValue(productArg, Product.class);

        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.postForObject("http://localhost:8080/products", product, String.class);

        System.out.println(response);
    }
}

推荐阅读