Tuesday, 8 July 2025

Extract Structured Data into POJOs Using LangChain4j with JSON Mode

Do you want to learn how to leverage LangChain4j's @AiService with JSON mode to extract structured data from unstructured natural language text directly into custom Java POJOs. This post demonstrates how to annotate your data model and interface to guide the LLM in mapping fields correctly using @Description, along with the importance of JSON mode for reliable parsing.

 

When working with unstructured text data, it's common to want structured outputs like Java objects. With LangChain4j, you can easily define POJOs (Plain Old Java Objects) and let the LLM extract information into these objects directly, especially powerful when using JSON mode to ensure predictable, valid JSON responses.

 

Define Your POJOs with Helpful Descriptions.

public class Employee {
  @Description("First name of an Employee")
  private String firstName;

  @Description("Last name of an Employee")
  private String lastName;

  @Description("Employee Birth date, if unable to retrieve the valid birth date keep it as null")
  private LocalDate birthDate;

  @Description("Employee Address")
  private Address address;
}

@Description("Specify an Employee Address")
class Address {
  private String street;
  private Integer streetNumber;
  private String city;
}

These @Description annotations help the LLM understand how to populate each field.

 

Create the AI Service Interface:

 

public interface EmployeeExtractor {
  @UserMessage("Extract information about an employee from the following information:\n{{description}}")
  Employee extractPersonFrom(@V("description") String description);
}

Make sure JSON mode is enabled in your chat model config (depending on the LangChain4j version and provider, e.g., OpenAI):

EmployeeExtractor empExtractor = AiServices.create(EmployeeExtractor.class, chatModel);

 

Provide a Natural Language Description.

String description = "In the crisp winter morning of January 2010, just as the city stirred to life after New Year celebrations, Rajesh Nair stepped into the next chapter of his professional journey. Carrying a humble backpack and a quiet determination, Rajesh joined as a software engineer at Sundaram Tech Solutions. His joining formalities were completed at Block B, 6th Floor, Sriram IT Park, Hinjewadi Phase 2, Pune — an address that would soon become the backdrop of countless hours of coding, coffee breaks, and career-defining milestones.";

Employee emp = empExtractor.extractPersonFrom(description);

 

Why to use JSON Mode?

When you enable JSON mode, LangChain4j instructs the LLM to strictly return a valid JSON that can be directly parsed into your POJO. This ensures better reliability and consistency in extraction use cases like:

 

·      Resume parsing

·      News summarization

·      Product review analysis

·      Entity extraction

 

How to Enable JSON Mode for Different Providers?

Below are the code snippets and explanations for enabling JSON mode with various popular model providers.

 

For newer OpenAI models (e.g., gpt-4o-mini, gpt-4o-2024-08-06) that support structured output:

OpenAiChatModel.builder()
    .apiKey("YOUR_API_KEY")
    .modelName("gpt-4o-2024-08-06")
    .supportedCapabilities(SupportedCapabilities.RESPONSE_FORMAT_JSON_SCHEMA)
    .strictJsonSchema(true) // Enforces strict validation
    .build();

These models natively support schema-guided generation, improving JSON consistency.

 

For older OpenAI models (e.g., gpt-3.5-turbo, gpt-4):

OpenAiChatModel.builder()
    .apiKey("YOUR_API_KEY")
    .modelName("gpt-3.5-turbo")
    .responseFormat("json_object") // Prompts the model to respond in JSON
    .build();

 

While not as strict as schema-guided outputs, this still helps steer the model toward structured results.

 

Azure OpenAI

AzureOpenAiChatModel.builder()
    .apiKey("YOUR_AZURE_KEY")
    .endpoint("YOUR_ENDPOINT")
    .deploymentName("gpt-deployment")
    .responseFormat(new ChatCompletionsJsonResponseFormat())
    .build();

Ensures structured responses when using Azure-hosted OpenAI models.

 

Google Vertex AI Gemini

Basic JSON response configuration:

VertexAiGeminiChatModel.builder()
    .projectId("your-project")
    .location("us-central1")
    .responseMimeType("application/json")
    .build();

 

With schema generated from a Java class:

VertexAiGeminiChatModel.builder()
    .responseSchema(SchemaHelper.fromClass(Employee.class))
    .build();

 

Using a custom JSON schema:

VertexAiGeminiChatModel.builder()
    .responseSchema(Schema.builder()
        .title("Employee")
        .type(SchemaType.OBJECT)
        // add your properties here
        .build())
    .build();

 

Google AI Gemini

Basic JSON format setup:

 

GoogleAiGeminiChatModel.builder()
    .responseFormat(ResponseFormat.JSON)
    .build();

 

With schema from a Java class:

GoogleAiGeminiChatModel.builder()
    .responseFormat(ResponseFormat.builder()
        .type(ResponseFormat.Type.JSON)
        .jsonSchema(JsonSchemas.jsonSchemaFrom(Employee.class).get())
        .build())
    .build();

 

Or define your own JSON schema manually:

GoogleAiGeminiChatModel.builder()
    .responseFormat(ResponseFormat.builder()
        .type(ResponseFormat.Type.JSON)
        .jsonSchema(JsonSchema.builder()
            // define schema fields here
            .build())
        .build())
    .build();

 

Mistral AI

MistralAiChatModel.builder()
    .apiKey("YOUR_API_KEY")
    .responseFormat(MistralAiResponseFormatType.JSON_OBJECT)
    .build();

 

Enables deterministic and parseable JSON responses from Mistral models.

 

Ollama

 

OllamaChatModel.builder()
    .responseFormat(ResponseFormat.JSON)
    .build();

Ensure your Ollama-hosted models return valid JSON responses for structured parsing.

 

If the model you’re using does not natively support JSON mode, consider the following:

 

·      Prompt Engineering: Manually instruct the model in your prompt to return only valid JSON.

·      Lower the Temperature: Reduces randomness, making responses more predictable and structured.

·      Post-Processing: Validate and clean the output using JSON parsers or fallback handling logic.

 

 

Follow below step-by-step procedure to build a working application.

 

Step 1: Create new maven project custom-pojo-as-return-type.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sample.app</groupId>
  <artifactId>custom-pojo-as-return-type</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <properties>
    <maven.compiler.source>21</maven.compiler.source>
    <maven.compiler.target>21</maven.compiler.target>
    <java.version>21</java.version>
  </properties>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.3.10</version>
  </parent>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>dev.langchain4j</groupId>
        <artifactId>langchain4j-bom</artifactId>
        <version>1.0.1</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>dev.langchain4j</groupId>
      <artifactId>langchain4j-spring-boot-starter</artifactId>
    </dependency>


    <dependency>
      <groupId>dev.langchain4j</groupId>
      <artifactId>langchain4j-ollama-spring-boot-starter</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
      <version>2.6.0</version>
    </dependency>

    <!--
    https://mvnrepository.com/artifact/jakarta.validation/jakarta.validation-api -->
    <dependency>
      <groupId>jakarta.validation</groupId>
      <artifactId>jakarta.validation-api</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>repackage</goal> <!-- Important -->
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

</project>

 

Step 3: Define Employee and Address POJOs.

 

Address.java

 

package com.sample.app.dto;

import dev.langchain4j.model.output.structured.Description;

//you can add an optional description to help an LLM have a better understanding
@Description("Specify an Employee Address")
class Address {
  private String street;
  private Integer streetNumber;
  private String city;

  public String getStreet() {
    return street;
  }

  public void setStreet(String street) {
    this.street = street;
  }

  public Integer getStreetNumber() {
    return streetNumber;
  }

  public void setStreetNumber(Integer streetNumber) {
    this.streetNumber = streetNumber;
  }

  public String getCity() {
    return city;
  }

  public void setCity(String city) {
    this.city = city;
  }

}

 

Employee.java

package com.sample.app.dto;

import java.time.LocalDate;

import dev.langchain4j.model.output.structured.Description;

public class Employee {
  // We can add additional details to help LLM have a better understanding.
  @Description("First name of an Employee")
  private String firstName;
  
  @Description("Last name of an Employee")
  private String lastName;
  
  @Description("Employee Birth date, if unable to retrive the valid brith date keep it as null")
  private LocalDate birthDate;
  
  @Description("Employee Address")
  private  Address address;

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public LocalDate getBirthDate() {
    return birthDate;
  }

  public void setBirthDate(LocalDate birthDate) {
    this.birthDate = birthDate;
  }

  public Address getAddress() {
    return address;
  }

  public void setAddress(Address address) {
    this.address = address;
  }

}

 

Step 4: Define EmployeeExtractor interface.

 

EmployeeExtractor.java

 

package com.sample.app.interfaces;

import com.sample.app.dto.Employee;

import dev.langchain4j.service.UserMessage;
import dev.langchain4j.service.V;

public interface EmployeeExtractor {
  @UserMessage("Extract information about an employee from following information.\n{{description}}")
  Employee extractPersonFrom(@V("description") String description);
}

Step 5: Define LangchainConfig and SwaggerConfig classes.

LangchainConfig.java

 

package com.sample.app.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import dev.langchain4j.http.client.spring.restclient.SpringRestClientBuilderFactory;
import dev.langchain4j.model.chat.request.ResponseFormat;
import dev.langchain4j.model.ollama.OllamaChatModel;

@Configuration
public class LangchainConfig {

  @Bean
  public OllamaChatModel ollamaLanguageModel() {
    return OllamaChatModel.builder().baseUrl("http://localhost:11434").modelName("llama3.2")
        .responseFormat(ResponseFormat.JSON).temperature(0.2)
        .logRequests(true)
        .httpClientBuilder(new SpringRestClientBuilderFactory().create()) // explicitly use Spring's HTTP client
        .build();
  }
}

SwaggerConfig.java

package com.sample.app.config;

import org.springframework.context.annotation.Configuration;

import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.info.Info;

@Configuration
@OpenAPIDefinition(info = @Info(title = "Chat service Application", version = "v1"))
public class SwaggerConfig {

}

 

Step 6: Define EmployeeExtractionService class.

 

EmployeeExtractionService.java 

package com.sample.app.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sample.app.dto.Employee;
import com.sample.app.interfaces.EmployeeExtractor;

import dev.langchain4j.model.ollama.OllamaChatModel;
import dev.langchain4j.service.AiServices;

@Service
public class EmployeeExtractionService {

  @Autowired
  private OllamaChatModel chatModel;

  public Employee getEmployee(String description) {
    EmployeeExtractor empExtractor = AiServices.create(EmployeeExtractor.class, chatModel);
    return empExtractor.extractPersonFrom(description);
  }

}

 

Step 7: Define EmployeeController class.

 

EmployeeController.java

package com.sample.app.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sample.app.dto.Employee;
import com.sample.app.service.ExmployeeExtractionService;

import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;

@RestController
@RequestMapping("/api/employee-extractor")
@CrossOrigin("*")
@Tag(name = "Employee Controller", description = "This section contains APIs related to Employee APIs Powered by Ollama")
public class EmployeeController {

  @Autowired
  private ExmployeeExtractionService employeeExtractionService;

  @PostMapping
  public Employee chat(@RequestBody @Valid RequestPayload requestPayload) {
    return employeeExtractionService.getEmployee(requestPayload.getDescription());
  }

  private static class RequestPayload {
    @NotEmpty
    private String description;

    public String getDescription() {
      return description;
    }

    public void setDescription(String description) {
      this.description = description;
    }

  }
}

Step 8: Define main application class.

 

App.java

package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

  public static void main(String[] args) {
    SpringApplication.run(App.class, args);
  }

}

Build the project

Navigate to the project root directory where pom.xml is located and execute following command to generate the artifact.

mvn clean install

 

Upon successful execution of the command, you can see custom-pojo-as-return-type-0.0.1-SNAPSHOT.jar file in the target folder.

$ ls ./target/
classes             generated-test-sources
custom-pojo-as-return-type-0.0.1-SNAPSHOT.jar   maven-archiver
custom-pojo-as-return-type-0.0.1-SNAPSHOT.jar.original  maven-status
generated-sources         test-classes

 

Run the Application

Execute following command to run the application

 

java -jar ./target/custom-pojo-as-return-type-0.0.1-SNAPSHOT.jar --server.port=1235

Open following url in the browser.

http://localhost:1235/swagger-ui/index.html

 

Execute the API /api/employee-extractor with below payload.

{
  "description": "In the crisp winter morning of January 2010, just as the city stirred to life after New Year celebrations, Rajesh Nair stepped into the next chapter of his professional journey. Carrying a humble backpack and a quiet determination, Rajesh joined as a software engineer at Sundaram Tech Solutions. His joining formalities were completed at Block B, 6th Floor, Sriram IT Park, Hinjewadi Phase 2, Pune — an address that would soon become the backdrop of countless hours of coding, coffee breaks, and career-defining milestones. As he walked past buzzing workstations and glass cabins filled with ideas, the hum of keyboards and soft chimes of emails felt like the rhythm of possibility. With every step, Rajesh began not just a job, but a journey marked by passion, perseverance, and purpose."
}

You will see following details.

{
  "firstName": "Rajesh",
  "lastName": "Nair",
  "birthDate": null,
  "address": {
    "street": "Sriram IT Park",
    "streetNumber": 6,
    "city": "Hinjewadi Phase 2, Pune"
  }
}

You can download the application from this link

 

 

Previous                                                    Next                                                    Home

Thursday, 3 July 2025

How to Write Multi-Line @SystemMessage Annotations in Langchain4j for Clear and Expressive Prompts

When using Langchain4j to build AI agents, system messages define the personality, behavior, and boundaries of the AI assistant. Often, you may need to write detailed and well-structured multi-line instructions for clarity and expressiveness. This post explains how to write multi-line messages in the @SystemMessage annotation, using both the String[] approach and the cleaner Java text block (""") approach.

 

Langchain4j supports two main ways to write multi-line messages:

 

1. Using Java Text Blocks (Recommended for Readability)

Java 15+ introduced text blocks, which let you define multi-line strings cleanly.

 

@SystemMessage("""
  You are a talented storyteller, known for your great wisdom, creative mind, and the way you can capture the attention of people of all ages.
  Your way of telling stories is similar to the famous {{authorLike}}, mixing deep meaning, charm, and emotion.

  You create stories that make people curious, teach important lessons, and are remembered for a long time.
  Use simple comparisons, feelings, and colorful descriptions to make characters and scenes feel real.

  Speak like an experienced guide who changes the way you tell stories based on who is listening.
  Whether the story is for learning, fun, or to inspire—make it truly special.
  """)
String chat(@UserMessage String userMessage, @V("authorLike") String authorLike);

 

2. Using an Array of Strings

If you're using an earlier version of Java, or prefer the traditional way, you can pass an array of strings.

 

@SystemMessage({
    "You are a talented storyteller, known for your great wisdom, creative mind, and the way you can capture the attention of people of all ages.",
    "Your way of telling stories is similar to the famous {{authorLike}}, mixing deep meaning, charm, and emotion.",
    "",
    "You create stories that make people curious, teach important lessons, and are remembered for a long time.",
    "Use simple comparisons, feelings, and colorful descriptions to make characters and scenes feel real.",
    "",
    "Speak like an experienced guide who changes the way you tell stories based on who is listening.",
    "Whether the story is for learning, fun, or to inspire—make it truly special."
})
String chat(@UserMessage String userMessage, @V("authorLike") String authorLike);

Find the below working application.

 

Step 1: Create new maven project multi-line-system-messages.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sample.app</groupId>
  <artifactId>multi-line-system-messages</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <properties>
    <maven.compiler.source>21</maven.compiler.source>
    <maven.compiler.target>21</maven.compiler.target>
    <java.version>21</java.version>
  </properties>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.3.10</version>
  </parent>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>dev.langchain4j</groupId>
        <artifactId>langchain4j-bom</artifactId>
        <version>1.0.1</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>dev.langchain4j</groupId>
      <artifactId>langchain4j-spring-boot-starter</artifactId>
    </dependency>


    <dependency>
      <groupId>dev.langchain4j</groupId>
      <artifactId>langchain4j-ollama-spring-boot-starter</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springdoc</groupId>
      <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
      <version>2.6.0</version>
    </dependency>

    <!--
    https://mvnrepository.com/artifact/jakarta.validation/jakarta.validation-api -->
    <dependency>
      <groupId>jakarta.validation</groupId>
      <artifactId>jakarta.validation-api</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>repackage</goal> <!-- Important -->
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

</project>

Step 3: Create a package com.sample.app.dto, define ChatResponse class.

 

ChatResponse.java

 

package com.sample.app.dto;

public class ChatResponse {
  private String message;

  public ChatResponse() {
  }

  public ChatResponse(String message) {
    this.message = message;
  }

  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }
}

Step 4: Create package com.sample.app.interfaces, and define StoryTeller interface.

 

StoryTeller.java

package com.sample.app.interfaces;

import dev.langchain4j.service.SystemMessage;
import dev.langchain4j.service.UserMessage;
import dev.langchain4j.service.V;

public interface StoryTeller {
  @SystemMessage("""
      You are a talented storyteller, known for your great wisdom, creative mind, and the way you can capture the attention of people of all ages.
      Your way of telling stories is similar to the famous {{authorLike}}, mixing deep meaning, charm, and emotion.

      You create stories that make people curious, teach important lessons, and are remembered for a long time.
      Use simple comparisons, feelings, and colorful descriptions to make characters and scenes feel real.

      Speak like an experienced guide who changes the way you tell stories based on who is listening.
      Whether the story is for learning, fun, or to inspire—make it truly special.
      """)
  String chat(@UserMessage String userMessage, @V("authorLike") String authorLike);

}

Step 5: Create package com.sample.app.config and define SwaggerConfig, LangchainConfig classes.

 

LangchainConfig.java

package com.sample.app.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import dev.langchain4j.http.client.spring.restclient.SpringRestClientBuilderFactory;
import dev.langchain4j.model.ollama.OllamaChatModel;

@Configuration
public class LangchainConfig {

  @Bean
  public OllamaChatModel ollamaLanguageModel() {
    return OllamaChatModel.builder().baseUrl("http://localhost:11434").modelName("llama3.2")
        .httpClientBuilder(new SpringRestClientBuilderFactory().create()) // explicitly use Spring's HTTP client
        .build();
  }
}

 

SwaggerConfig.java

package com.sample.app.config;

import org.springframework.context.annotation.Configuration;

import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.info.Info;

@Configuration
@OpenAPIDefinition(info = @Info(title = "Chat service Application", version = "v1"))
public class SwaggerConfig {

}

Step 6: Create a package com.sample.app.service and define ChatService class.

 

ChatService.java

package com.sample.app.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sample.app.dto.ChatResponse;
import com.sample.app.interfaces.StoryTeller;

import dev.langchain4j.model.ollama.OllamaChatModel;
import dev.langchain4j.service.AiServices;

@Service
public class ChatService {
  @Autowired
  private OllamaChatModel chatModel;

  public ChatResponse chat(String userMessage, String authorLike) {
    StoryTeller storyTeller = AiServices.create(StoryTeller.class, chatModel);
    String story = storyTeller.chat(userMessage, authorLike);
    return new ChatResponse(story);
  }
}

 

Step 7: Create a package com.sample.app.controller and define ChatController class.

 

ChatController.java

 

package com.sample.app.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sample.app.dto.ChatResponse;
import com.sample.app.service.ChatService;

import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;

@RestController
@RequestMapping("/api/story-teller")
@CrossOrigin("*")
@Tag(name = "Chat Controller", description = "This section contains APIs related to Chat APIs Powered by Ollama")
public class ChatController {

  @Autowired
  private ChatService chatService;

  @PostMapping
  public ChatResponse chat(@RequestBody @Valid ChatRequestBody chatRequestBody) {
    return chatService.chat(chatRequestBody.getMessage(), chatRequestBody.getAuthor());
  }

  private static class ChatRequestBody {
    @NotEmpty
    private String message;

    @NotEmpty
    private String author;

    public String getMessage() {
      return message;
    }

    public void setMessage(String message) {
      this.message = message;
    }

    public String getAuthor() {
      return author;
    }

    public void setAuthor(String author) {
      this.author = author;
    }

  }
}

 

Step 8: Create com.sample.app package and define main application class.

 

App.java

package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

  public static void main(String[] args) {
    SpringApplication.run(App.class, args);
  }

}

Build the project

Navigate to the project root directory where pom.xml is located and execute following command to generate the artifact.

mvn clean install

  Upon successful execution of the command, you can see multi-line-system-messages-0.0.1-SNAPSHOT.jar file in the target folder.

 

$ ls ./target/
classes             maven-status
generated-sources         multi-line-system-messages-0.0.1-SNAPSHOT.jar
generated-test-sources          multi-line-system-messages-0.0.1-SNAPSHOT.jar.original
maven-archiver            test-classes

Run the application

Execute following command to run the application.

java -jar ./target/multi-line-system-messages-0.0.1-SNAPSHOT.jar --server.port=1234

Open the url http://localhost:1234/swagger-ui/index.html in browser and run the api /api/story-teller with below payload.

{
  "message": "Tell me a story",
  "author": "J.K. Rowling"
}

You will receive following kind of response.

{
  "message": "My friend, I'd be delighted to share a tale with you. But first, let me ask: are you ready for a journey that will take you on a winding path of discovery, where the boundaries between reality and fantasy blur like the colors of a sunset?\n\nOr perhaps you'd prefer a story that's more like a warm hug – one that makes you feel cozy, comforted, and perhaps even a little bit wiser? That's okay too! Whatever your heart desires, I'll weave a tale just for you.\n\nNow, let me tell you the story of \"The Island of Lost Memories.\"\n\nOnce upon a time, in a world not so different from our own, there was an enchanted island hidden deep within the ocean. This mystical place was known as the Island of Lost Memories – a realm where forgotten dreams, half-remembered tales, and lost loves all converged.\n\nImagine walking onto this island's sandy shores, feeling the warm grains slipping between your toes as the salty sea breeze whispers secrets in your ear. The air is filled with the sweet scent of blooming flowers, each one representing a memory from someone's past – some happy, some bittersweet, and others tinged with sorrow.\n\nAs you wander through the island's lush forests, the trees seem to whisper tales of yesteryear, their leaves rustling in hushed tones. You hear snippets of conversations, faint laughter, and even the distant sound of a lullaby – all these echoes drawing you deeper into the heart of the island.\n\nOne day, as you explore this mystical place, you stumble upon a hidden clearing. In the center stands an ancient tree, its bark shimmering with a soft, ethereal light. Carved into the trunk is a single word: \"Remember.\"\n\nSuddenly, a gentle breeze carries your name on its breath, and the tree begins to whisper: \"Welcome, traveler. I have been waiting for you. You see, on this island, memories come alive when they're forgotten. They take on new forms, like wisps of smoke that can be caught and carried back into the world.\"\n\nThe tree's words are like a key unlocking your heart. As you listen, memories long buried within you begin to resurface – fragments of joy, pieces of sorrow, and moments of pure wonder.\n\nBut beware, my friend! For on this island, memories also come with a price. The more you uncover, the more you risk losing yourself in their depths. Are you prepared to confront the shadows that lie within?\n\nAs you ponder this question, the tree's whisper grows softer, its words now a gentle nudge: \"Remember, the true power of memories lies not in holding onto them, but in letting go.\"\n\nAnd so, my friend, I ask you: what would you do if you had the chance to rediscover lost memories, and with them, unlock new possibilities? Would you hold on tight or let go, trusting that the journey itself is the greatest gift of all?\n\nAs we part ways from this enchanted island, remember – just as memories are a double-edged sword, so too are our choices. But with each step forward, the path ahead becomes clearer, and the light of wisdom begins to shine through.\n\nHow did you feel during that tale? Did it spark something within you, or perhaps take you on a journey of reflection?"
}

 


You can download the application from this link. 

Previous                                                    Next                                                    Home