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

Environment Variables

Settings from outside.

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

Passwords, and server addresses, shouldn't be written in files that everyone can read. On a real server, settings often come from environment variables instead.

  • No passwords in files
  • Settings from outside
  • Environment variables

Where settings come from

Spring Boot reads settings from many places. Command line arguments win over everything. Then environment variables. Then the profile files, and finally application dot properties. So a server can override any setting, without changing a file.

keyvalue
1stcommand line: --shop.name=X
2ndenvironment variables: SHOP_NAME
3rdapplication-{profile}.properties
4thapplication.properties

Naming environment variables

Environment variables are usually written in capitals, with underscores. Spring converts them for you. Shop_name sets shop dot name. And spring_datasource_password sets the database password.

keyvalue
shop.nameSHOP_NAME
shop.discountSHOP_DISCOUNT
spring.datasource.passwordSPRING_DATASOURCE_PASSWORD
Rulecapitals, dots → underscores

Overriding a setting

The properties file says ten percent off. This time, we start the app with an environment variable, shop discount equals twenty five. The runner prints the name, and the discount. Run it. The name comes from the file. But the discount is twenty five, from the environment variable.

StartupRunner.javajava
@Component
public class StartupRunner implements CommandLineRunner {

    private final ShopProperties shop;

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

    @Override
    public void run(String... args) {
        System.out.println(shop.name() + ", " + shop.discount() + "% off");
    }
}
Output
Corner Books, 25% off
Also uses ShopProperties.java
@ConfigurationProperties("shop")
public record ShopProperties(String name, int discount) {}
Also uses BookshopApplication.java
@SpringBootApplication
@ConfigurationPropertiesScan
public class BookshopApplication {
    public static void main(String[] args) {
        SpringApplication.run(BookshopApplication.class, args);
    }
}
Also uses application.properties
shop.name=Corner Books
shop.discount=10
Also uses _env
SHOP_DISCOUNT=25

Summary

Environment variables override settings files, using capitals and underscores. Command line arguments override both. Next, some practice.

Key takeaways
  • SHOP_DISCOUNT=25
  • Overrides the file
  • --key=value wins
Next up: Practice: A Configurable Shop — your turn