猿问

如何在实例化 Java Spring Webflux 时修改或更新 POJO 模型

我正在使用适用于 Java 的 Google Maps Geocoding API。我有一个基本地址 POJO。我想要做的是在lat 属性上运行createLatCord方法,主体响应是地址、城市、州和邮政编码


我不知道我还应该在哪里修改,在模型本身,Controller或Service/Repository处?


方法我需要在创建时在 lat 属性上运行


private double createLatCord() throws InterruptedException, ApiException, IOException {

    GeoApiContext context = new 

    GeoApiContext.Builder().apiKey("abc").build();

    GeocodingResult[] results = GeocodingApi.geocode(context, address+city+state+zipcode).await();

//  Gson gson = new GsonBuilder().setPrettyPrinting().create();

    return results[0].geometry.location.lat;

}

模型 :



// all the imports ...


public class User {


    private String address;

    private String zipcode;

    private String city;

    private String state;

    private double lat; // <-- Run createLatCord method on this property

    @Id

    private String id;


    public User() {

    }


    public User(String address, String zipcode, String city, String state, double lat) throws InterruptedException, ApiException, IOException {

        this.address = address;

        this.city = city;

        this.state = state;

        this.zipcode = zipcode;

        this.lat = lat;

    }


// GETTERS AND SETTERS HERE FOR THE ABOVE

// Leaving it out cause it's alot


}


控制器:


@PostMapping(path = "", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)

public Mono<User> createUser(@RequestBody Mono<User> user) {

     return userService.createUser(user);

}

服务/存储库:


@Override

public Mono<User> createUser(Mono<User> userMono) {

   return reactiveMongoOperations.save(userMono);

}

互换的青春
浏览 124回答 1
1回答

慕姐4208626

如果我做对了,你想在保存用户时更新纬度。由于您的服务已经收到一个 Mono,您可以对其进行平面映射以调用 google api,然后调用存储库。它会是这样的:@Override public&nbsp;Mono<User>&nbsp;createUser(Mono<User>&nbsp;userMono)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;userMono.flatMap(user&nbsp;->&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;methodToCallGoogleApiAndSetValueToUser(user)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.subscribe(reactiveMongoOperations::save) }有一点是methodToCallGoogleApiAndSetValueToUser应该返回一个带有更新用户的 Mono。希望这可能会有所帮助!
随时随地看视频慕课网APP

相关分类

Java
我要回答