AI Hints
Home›Spring Boot Tutorial›CommandLineRunner, Environment Variables and Practice: A Configurable Shop
Spring Boot · Lesson 45 of 120

Practice: A Configurable Shop

Your turn.

⏱ 2 min read▶ Video at 1:00:08🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

Let's practise with configuration. Our shop's opening hours will come from settings, not from the code.

  • Opening hours
  • From settings
  • Not from code

The settings and the record

The settings hold the name, the opening hour, and the closing hour. Shop properties loads them. And is open at checks an hour, against the opening times. The main class has at Configuration Properties Scan, which finds records like this one automatically.

ShopProperties.javajava
@ConfigurationProperties("shop")
public record ShopProperties(String name, int opens, int closes) {

    public boolean isOpenAt(int hour) {
        return hour >= opens && hour < closes;
    }
}

Open or closed?

Your turn. Pause the video, and try this. Write a controller that receives shop properties. Add GET slash open, with an hour parameter. Answer whether the shop is open, or closed, at that hour. Here is one solution. The controller asks the record. At ten, the shop is open. At eight, and at eighteen, it's closed.

✍️ Exercise: Open or closed?

GET /open?hour=10 → "Corner Books is open at 10:00" (or closed). Use the ShopProperties record (opens=9, closes=18).

Show hint

inject ShopProperties, then shop.isOpenAt(hour)

Show solution
ShopController.javajava
@RestController
public class ShopController {

    private final ShopProperties shop;

    public ShopController(ShopProperties shop) {
        this.shop = shop;
    }

    @GetMapping("/open")
    public String open(@RequestParam int hour) {
        String state = shop.isOpenAt(hour) ? "open" : "closed";
        return shop.name() + " is " + state + " at " + hour + ":00";
    }
}
Output
$ curl "localhost:8080/open?hour=10"
Corner Books is open at 10:00
$ curl "localhost:8080/open?hour=8"
Corner Books is closed at 8:00
$ curl "localhost:8080/open?hour=18"
Corner Books is closed at 18:00

What module five taught

Settings live in application dot properties, or YAML. At Value reads one setting, and at Configuration Properties reads a group. Profiles switch settings per environment. Loggers report what happens. And environment variables override everything in files.

keyvalue
Filesproperties or YAML
Read@Value, @ConfigurationProperties
Profilesapplication-dev.properties
Overrideenv vars, --args

Summary

Your app can now be configured without touching the code. That's the end of module five. Next module, databases, and JPA.

Key takeaways
  • Settings files
  • Profiles
  • Environment variables
Next up: Why a Database — data that survives