Properties, profiles and SpEL

Key idea
Configuration that changes between environments lives outside the code. Spring's `Environment` combines several property sources (files, environment variables, system properties) and knows which profiles are active; `@Value` injects their values and `@Profile` decides which beans exist.
In the box
The box name and capacity were written in the code. Move them to a properties file, read them with @Value and the Environment, compute values with SpEL and switch implementations per environment with @Profile.
ApplicationContextHardcodedSettings

Only HardcodedSettings is in the context, highlighted in red: the values are written in the code.

Outside the context the box.properties file appears and sends @PropertySource to the Environment; both are highlighted. BoxSettings is next to them.

The Environment, connected to the file, injects ${box.name} into BoxSettings, highlighted.

coachRoster, highlighted together with BoxSettings, injects the result of #{coachRoster.size()} into it.

The -Dbox.name system property appears and sends CrossFit Sur to the Environment, both highlighted: it beats the file.

PlaceholderConfigurer, highlighted in amber, sends resolve ${…} to BoxSettings: with it, a placeholder without a value makes startup fail.

WelcomeService and the two mailers appear, ConsoleMailer and SmtpMailer, highlighted. With no active profile, the default packet comes from ConsoleMailer.

Only SmtpMailer is left, highlighted together with WelcomeService, which receives the prod packet.

Final view: the file and the system property feed the Environment, which feeds BoxSettings and WelcomeService; below, the two mailers per profile.

Step 1 of 9

Hard-wired values

HardcodedSettings returns the box name, capacity and plans written in the code.

If tomorrow you open a second box with capacity 20, or want a small capacity in tests, you have to change code and recompile. Same for environment-dependent things: in development e-mails should go to the console, not through SMTP.

Step 2 of 9

A file and the Environment

The values move to box.properties, and @PropertySource("classpath:box.properties") adds it to the Environment.

The Environment is the Spring component that knows two things:

  • Properties: an ordered list of property sources. When looking up a key, the first source that has it wins.
  • Profiles: which ones are active and which is the default profile.

You can inject it like any bean and ask it getProperty("box.name"), with a default value or asking for a type: getProperty("box.capacity", Integer.class).

Step 3 of 9

@Value and ${…} placeholders

Usually you don't ask the Environment by hand; you inject the value directly with @Value:

  • @Value("${box.name}"): a property placeholder. Spring replaces it with the value.
  • @Value("${box.capacity:10}"): what comes after the colon is the default value if the key doesn't exist.
  • Spring converts the text to the parameter type: "12" becomes an int.

@Value works on constructor parameters (as here), fields and setters.

Step 4 of 9

SpEL: expressions with #{…}

When you need to compute, you use the Spring Expression Language with #{…}:

  • #{${box.capacity} * 2}: a placeholder inside an expression. ${…} is resolved first and then SpEL does the arithmetic: 24.
  • #{coachRoster.size() * 6}: calls a method on another bean, by name.
  • #{systemProperties['box.tz'] ?: 'Europe/Madrid'}: reads a system property with the Elvis operator as plan B.
  • #{'${box.plans}'.split(',')}: splits the comma-separated list.

More SpEL pieces that show up on the exam: T(java.lang.Math).max(a, b) for classes and static methods, systemEnvironment['HOME'], safe navigation bean?.field and logical and comparison operators.

Step 5 of 9

Who wins? The order of sources

The same key can be in several places. In a standard Spring application (StandardEnvironment), the lookup order is:

  1. JVM system properties (-Dbox.name=…).
  2. Operating system environment variables.
  3. Files added with @PropertySource, in declaration order.

The test starts with -Dbox.name=CrossFit Sur, and it beats the file. It also shows that getRequiredProperty throws IllegalStateException when the key is missing, whereas getProperty would return null.

Step 6 of 9

Trap: the ${…} that doesn't exist

What if a @Value("${box.owner}") asks for a key nobody defines? It depends:

  • Without PropertySourcesPlaceholderConfigurer, Spring uses a lenient resolver and the bean gets the literal text "${box.owner}". The mistake goes unnoticed.
  • With it, resolution is strict and startup fails: "Could not resolve placeholder 'box.owner'".

That's why PropsConfig declares it with a static @Bean method. It's a BeanFactoryPostProcessor: it must exist before the other beans, and being static, Spring doesn't need to create the configuration class first.

Step 7 of 9

@Profile: beans per environment

Values aren't the only thing that changes between environments; sometimes the part changes. In development e-mails go to the console and in production, through SMTP.

  • @Profile({"dev", "default"}) ConsoleMailer: exists if dev is active… or if no profile is active (then the default profile is activated).
  • @Profile("prod") SmtpMailer: production only.
  • @Profile("!prod") AuditMailListener: everywhere except production. There are also & and |.

A bean without @Profile is always created. @Profile works on @Component classes, on @Configuration classes (affecting all their @Beans) and on @Bean methods.

Step 8 of 9

Activating a profile

Ways to activate profiles:

  • The spring.profiles.active=prod property (as -D, the SPRING_PROFILES_ACTIVE environment variable or, in Boot, in application.properties).
  • In code: ctx.getEnvironment().setActiveProfiles("prod") before register() and refresh().
  • In tests: @ActiveProfiles("prod").

With prod active, WelcomeService gets SmtpMailer; ConsoleMailer and AuditMailListener don't exist.

Step 9 of 9

Recap

  • Sources → Environment → @Value("${…}"). Default value with :.
  • SpEL with #{…}: arithmetic, beans by name, T(...), systemProperties, Elvis.
  • Order in plain Spring: -D > environment variables > @PropertySource.
  • PropertySourcesPlaceholderConfigurer (static @Bean) makes ${…} strict; Boot brings it out of the box.
  • @Profile decides which beans exist; with no active profiles, default applies.

Cheatsheet →

Code

HardcodedSettings.java

/** Before: every value is baked into the code. Changing the capacity means a new build. */
public class HardcodedSettings {
    public String name() {
        return "CrossFit Norte";
    }

    public int capacity() {
        return 12;                // same in dev, in tests and in production
    }

    public List<String> plans() {
        return List.of("monthly", "ten-pack", "drop-in");
    }
}

PropsConfig.java

@Configuration
@ComponentScan(basePackageClasses = PropsConfig.class, excludeFilters =
    @ComponentScan.Filter(type = org.springframework.context.annotation.FilterType.REGEX, pattern = ".*\\.web\\..*"))
@PropertySource("classpath:box.properties") // adds the file to the Environment
public class PropsConfig {

    @Bean // static: it is a BeanFactoryPostProcessor and must exist before the other beans
    public static PropertySourcesPlaceholderConfigurer placeholders() {
        return new PropertySourcesPlaceholderConfigurer(); // strict: an unknown ${…} fails at startup
    }
}

BoxSettings.java

public BoxSettings(@Value("${box.name}") String name,                // ${…}: a property placeholder
                   @Value("${box.capacity:10}") int capacity,       // ":10" is the default if missing
                   @Value("#{'${box.plans}'.split(',')}") List<String> plans, // split "a,b,c" with SpEL
                   @Value("#{${box.capacity} * 2}") int waitlist,             // #{…}: SpEL, placeholder inside
                   @Value("#{coachRoster.size() * 6}") int classesPerDay,      // a bean, by name
                   @Value("#{systemProperties['box.tz'] ?: 'Europe/Madrid'}") String timezone) { // Elvis
                       // …
                   }

BoxSettings.java

public BoxSettings(@Value("${box.name}") String name,                // ${…}: a property placeholder
                   @Value("${box.capacity:10}") int capacity,       // ":10" is the default if missing
                   @Value("#{'${box.plans}'.split(',')}") List<String> plans, // split "a,b,c" with SpEL
                   @Value("#{${box.capacity} * 2}") int waitlist,             // #{…}: SpEL, placeholder inside
                   @Value("#{coachRoster.size() * 6}") int classesPerDay,      // a bean, by name
                   @Value("#{systemProperties['box.tz'] ?: 'Europe/Madrid'}") String timezone) { // Elvis
                       // …
                   }

EnvironmentTest.java

@Test
void aSystemPropertyBeatsThePropertiesFile() {
    System.setProperty("box.name", "CrossFit Sur");          // like -Dbox.name=… on the command line
    try (var ctx = new AnnotationConfigApplicationContext(PropsConfig.class)) {
        Environment env = ctx.getEnvironment();

        assertThat(env.getProperty("box.name")).isEqualTo("CrossFit Sur");
        assertThat(ctx.getBean(BoxSettings.class).name()).isEqualTo("CrossFit Sur");
        assertThat(env.getProperty("box.capacity", Integer.class)).isEqualTo(12); // typed lookup
        assertThatThrownBy(() -> env.getRequiredProperty("box.owner"))
            .isInstanceOf(IllegalStateException.class);       // required + missing = exception
    }
}

PlaceholderTest.java

@Test
void withoutAPlaceholderConfigurerAnUnknownKeyStaysLiteral() {
    try (var ctx = new AnnotationConfigApplicationContext(Owner.class)) {
        assertThat(ctx.getBean(Owner.class).owner).isEqualTo("${box.owner}"); // lenient fallback
    }
}

@Test
void withPropertySourcesPlaceholderConfigurerItFailsAtStartup() {
    assertThatThrownBy(() -> new AnnotationConfigApplicationContext(
            Owner.class, PropertySourcesPlaceholderConfigurer.class))
        .isInstanceOf(BeanCreationException.class)
        .hasStackTraceContaining("Could not resolve placeholder 'box.owner'");
}

ConsoleMailer.java

@Component
@Profile({"dev", "default"}) // active in dev, and when no profile is active at all
public class ConsoleMailer implements Mailer {
    @Override
    public String send(String to, String text) {
        return "console → " + to + ": " + text;
    }
}

ProfileTest.java

@Test
void activatingProdSwapsTheMailer() {
    try (var ctx = new AnnotationConfigApplicationContext()) {
        ctx.getEnvironment().setActiveProfiles("prod");     // BEFORE register/refresh
        ctx.register(PropsConfig.class);
        ctx.refresh();

        assertThat(ctx.getBean(WelcomeService.class).welcome("Ana")).startsWith("smtp");
        assertThat(ctx.getBeansOfType(ConsoleMailer.class)).isEmpty();      // "dev", "default": off
        assertThat(ctx.getBeansOfType(AuditMailListener.class)).isEmpty();  // "!prod": off
        assertThat(ctx.getBean(SmtpMailer.class)).isNotNull();
    }
}

BoxSettings.java

public BoxSettings(@Value("${box.name}") String name,                // ${…}: a property placeholder
                   @Value("${box.capacity:10}") int capacity,       // ":10" is the default if missing
                   @Value("#{'${box.plans}'.split(',')}") List<String> plans, // split "a,b,c" with SpEL
                   @Value("#{${box.capacity} * 2}") int waitlist,             // #{…}: SpEL, placeholder inside
                   @Value("#{coachRoster.size() * 6}") int classesPerDay,      // a bean, by name
                   @Value("#{systemProperties['box.tz'] ?: 'Europe/Madrid'}") String timezone) { // Elvis
                       // …
                   }

Quiz

1. What's the difference between @Value("${box.capacity}") and @Value("#{box.capacity}")?

2. You have @Value("${box.capacity:10}"). What is injected if box.capacity=12 is in the file?

3. A Spring context (without Boot) doesn't declare PropertySourcesPlaceholderConfigurer and a bean has @Value("${box.owner}"), which doesn't exist. What happens?

4. Why must the @Bean method returning a PropertySourcesPlaceholderConfigurer be static?

5. No profile is active. Which bean is created, @Profile({"dev", "default"}) ConsoleMailer or @Profile("prod") SmtpMailer?

6. Which profile expression enables a bean in every environment except production?

Cheatsheet → · Mock exam →

Run it