Builder -Designmuster für den API -Endpunkt Spring StartJava

Java-Forum
Guest
 Builder -Designmuster für den API -Endpunkt Spring Start

Post by Guest »

Ich habe versucht, ein Builder -Designmuster für eine Modellklasse zu verwenden. Ich muss einige obligatorische Dateien und einige optionale Felder haben. Dieses Design könnte mir in diesem Szenario helfen. Ich verwende Spring Boot und Java 22 und erstellte eine Modellklasse für einen der Endpunkte. Ich habe auch die Importe aufgenommen und einen Großteil des unnötigen Code entfernt, da der Fokus das Prioritätsfeld ist. Dies ist die Klasse: < /p>

Code: Select all

import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

public class ConfigRequestModel {
private String id;
//other mandatory fields
private Optional priority;
// other optional fields

public ConfigRequestModel(){}

public ConfigRequestModel(ConfigRequestModelBuilder builder) {
this.id = builder.id;
//other mandatory and optional fields
this.priority = builder.priority;
}

public static class ConfigRequestModelBuilder{
private final String id;
//other mandatory and optional fields
private Optional priority;

public ConfigRequestModelBuilder(String id,
//other mandatory fields) {
//mandatory fields

}

public void map(HashMap map) {
if(frequency.isEmpty()){
this.map = new HashMap();
}else {
this.map = map;
}
}

public void setPriority(Optional priority) {

this.priority = priority.isPresent() ? priority : Optional.empty();

//            if (priority.isPresent()) {
//                this.priority = Optional.empty();
//            }else {
//                this.priority = priority;
//            }
}

public void date(Optional date) {
if (date.isPresent()){
this.date = Optional.empty();
}else {
this.date = date;
}
}
//rest of the setters

public String id() {
return id;
}
// rest of the getters
//equals
//hashCode
//toString
< /code>
So verwende ich die Priorität: < /p>
if (configRequestModel.getPriority().isEmpty())
< /code>
Ich habe diesen Fehler erhalten: < /p>
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.lang.NullPointerException: Cannot invoke "java.util.Optional.isEmpty()" because the return value of "com.upload_manager.UploadManager.model.uploadManager.ConfigRequestModel.getPriority()" is null] with root cause
< /code>
Es ist bizarr, weil Jackson den Bauherr standardmäßig anrufen sollte, da ich gelesen habe, dass er diese Muster erkennen kann. Darüber hinaus sollte die Priorität.ISpresent () 
funktionieren und optional.Empty () , nicht null . Bitte zögern Sie nicht, sie zu teilen.

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post