spring - 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 文档。但那些不符合要求。
请帮助解释一种方法或提供正确的文档来实现这一目标。
解决方案
一种方法是像这样实现 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);
}
}
推荐阅读
- java - 如何将用户名传递到 Spring Boot 安全性的 application.properties 的登录 SQL 代码中?
- php - Laravel 雄辩的条件关系
- javascript - 在 vue.js 中使用带有渲染函数的导入 sass 文件
- awk - 如果其中一列有字母,则跳过该行的操作 - bash
- oracle - CI 连接到 oracle 11g
- python - PyAudio 无法安装
- python - 在 Z3 中使用固定字符定义位向量
- android - 移动应用的 Google OAuth 同意屏幕的值
- javascript - 将 VNode 渲染为 html 字符串
- scala - Spark - 按用户 ID 减少输入文件