0
0
Spring Bootframework~30 mins

Environment variables in configuration in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Environment variables in configuration
📖 Scenario: You are building a Spring Boot application that needs to use environment variables to configure its behavior. This is common when deploying apps to different environments like development, testing, and production.
🎯 Goal: Create a Spring Boot application that reads a custom environment variable and uses it in the configuration to display a greeting message.
📋 What You'll Learn
Create a property in application.properties that reads an environment variable
Create a Spring Boot @Component class that uses @Value to inject the property
Write a method that returns the greeting message using the injected property
Add a @RestController with a GET endpoint to return the greeting message
💡 Why This Matters
🌍 Real World
Using environment variables for configuration is essential for deploying Spring Boot applications across different environments without changing code.
💼 Career
Many companies use environment variables to manage secrets, API keys, and environment-specific settings in their Spring Boot microservices.
Progress0 / 4 steps
1
Create application.properties with environment variable placeholder
Create a file named application.properties and add a property called app.greeting that reads the environment variable GREETING_MESSAGE with a default value of Hello, World!.
Spring Boot
Need a hint?

Use the syntax property=${ENV_VAR:defaultValue} to read environment variables in Spring Boot.

2
Create GreetingService component with @Value injection
Create a class named GreetingService annotated with @Component. Inject the property app.greeting into a private String field called greeting using @Value. Add a public method getGreeting() that returns the greeting string.
Spring Boot
Need a hint?

Use @Value("${app.greeting}") to inject the property into the field.

3
Create GreetingController with GET endpoint
Create a class named GreetingController annotated with @RestController. Inject GreetingService via constructor. Add a GET mapping method greet() mapped to /greet that returns the greeting string from GreetingService.getGreeting().
Spring Boot
Need a hint?

Use constructor injection for GreetingService and @GetMapping("/greet") for the endpoint.

4
Add main Spring Boot application class
Create a class named DemoApplication annotated with @SpringBootApplication. Add the main method that runs SpringApplication.run(DemoApplication.class, args).
Spring Boot
Need a hint?

The main class must have @SpringBootApplication and a main method to start the app.