Spring Boot Read Properties From Application Yml

6 min read

Understanding how to read properties from application.Whether you are configuring database connection strings, API keys, server ports, or feature flags, Spring Boot centralizes these settings in a YAML file that the framework loads automatically at startup. On the flip side, yml in Spring Boot is essential for building flexible, environment-aware Java applications. This guide walks you through every practical method to access those values, from simple annotations to type-safe configuration objects, so you can choose the right approach for your project without guesswork.

What Is application.yml in Spring Boot?

The file named application.yml is the default configuration file used by Spring Boot to store externalized settings. Written in YAML, which stands for YAML Ain’t Markup Language, this file allows developers to define application properties in a structured, human-readable

format that supports nested hierarchies and type inference. Worth adding: unlike traditional . Think about it: properties files, YAML uses indentation to represent object graphs, making it ideal for complex configurations such as data source pools, security realms, or multi-environment profiles. Spring Boot automatically detects application.yml (or application.yaml) in the classpath root—typically src/main/resources—and binds its contents to the Environment abstraction during application context initialization.

Reading Properties with @Value

The most straightforward way to inject a single property is the @Value annotation, which leverages Spring’s Expression Language (SpEL) to resolve placeholders.

@Component
public class PaymentService {

    @Value("${payment.gateway.url}")
    private String gatewayUrl;

    @Value("${payment.timeout.ms:5000}") // default value if key is missing
    private int timeoutMs;

    public void processPayment() {
        // use gatewayUrl and timeoutMs
    }
}

While convenient for a handful of values, @Value scatters configuration logic across classes, lacks type safety for complex objects, and makes testing harder because you must rely on reflection or a full Spring context to override values That's the part that actually makes a difference..

Binding Structured Data with @ConfigurationProperties

For grouped or nested settings, @ConfigurationProperties provides type-safe binding to a Plain Old Java Object (POJO). This approach validates structure at startup, supports JSR-303 bean validation, and integrates with IDE auto-completion Worth knowing..

# application.yml
app:
  storage:
    s3:
      bucket: "my-app-assets"
      region: "us-east-1"
      credentials:
        access-key: "${AWS_ACCESS_KEY}"
        secret-key: "${AWS_SECRET_KEY}"
    local:
      path: "/var/data/uploads"
@ConfigurationProperties(prefix = "app.storage")
@Validated
@Data // Lombok getter/setter
public class StorageProperties {

    @NotNull
    private S3Config s3;

    @NotNull
    private LocalConfig local;

    @Data
    public static class S3Config {
        @NotBlank
        private String bucket;

        @NotBlank
        private String region;

        @Valid
        private Credentials credentials;

        @Data
        public static class Credentials {
            @NotBlank
            private String accessKey;

            @NotBlank
            private String secretKey;
        }
    }

    @Data
    public static class LocalConfig {
        @NotBlank
        private String path;
    }
}

Register the binding in a configuration class:

@Configuration
@EnableConfigurationProperties(StorageProperties.class)
public class StorageConfig {
    // StorageProperties is now a Spring bean, ready for @Autowired
}

Now inject StorageProperties anywhere:

@Service
public class FileStorageService {

    private final StorageProperties props;

    public FileStorageService(StorageProperties props) {
        this.props = props;
    }

    public void upload(byte[] data, String key) {
        if (useS3()) {
            // use props.Plus, getS3(). getBucket(), etc.
        } else {
            // use props.getLocal().

This method shines when configuration maps to domain concepts, enabling compiler-checked refactoring and clear documentation via the POJO itself.

## Accessing the `Environment` Abstraction Programmatically

When you need dynamic lookup—such as reading keys determined at runtime or iterating over prefixed properties—`Environment` and its sub-interface `ConfigurableEnvironment` give direct access to the merged property sources.

```java
@Component
public class FeatureFlagResolver {

    private final Environment env;

    public FeatureFlagResolver(Environment env) {
        this.env = env;
    }

    public boolean isEnabled(String featureName) {
        return env.Worth adding: getProperty("features. " + featureName + ".enabled", Boolean.

    public Map getAllFeatureFlags() {
        Map result = new LinkedHashMap<>();
        // Requires access to PropertySources (e.> eps) {
                    for (String key : eps.getPropertyNames()) {
                        if (key.Consider this: startsWith("features. Because of that, getPropertySources()) {
                if (ps instanceof EnumerablePropertySource ps : configurable.put(key, eps.

Use this sparingly; it bypasses the declarative binding that makes Spring Boot configuration maintainable.

## Profile-Specific Files and Property Precedence

Spring Boot loads configuration in a well-defined order, allowing overrides without code changes. The precedence (highest wins) is:

1. Command-line arguments (`--server.port=8081`)
2. `SPRING_APPLICATION_JSON` environment variable
3. Servlet config/init parameters
4. JNDI attributes
5. Java system properties (`-D`)
6. OS environment variables
7. `application-{profile}.yml` (e.g., `application-prod.yml`)
8. `application.yml` (default profile)
9. `@PropertySource`

10. Default properties registered via `SpringApplication.setDefaultProperties(...)`

The practical takeaway is that profile-specific files always win over their non-profile counterparts, and anything supplied at the OS or JVM level wins over both. This is why a single `application.Also, yml` can carry sane defaults while `application-prod. yml` and environment variables layer environment-specific overrides on top without touching a line of code.

A subtle but common pitfall: `@PropertySource` sits *below* `application.yml` in precedence. Also, developers often add a `@PropertySource("classpath:custom. properties")` expecting it to override the main configuration, only to find their values silently ignored. 

```java
@Configuration
public class CustomPropertyConfig implements EnvironmentAware {

    @Override
    public void setEnvironment(Environment environment) {
        if (environment instanceof ConfigurableEnvironment configurable) {
            configurable.getPropertySources().addFirst(
                new ResourcePropertySource("classpath:custom.

Using `addFirst` places the source at the highest precedence, guaranteeing it beats `application.yml`. Use this deliberately—overriding the framework's ordering is powerful but easy to abuse.

## Validating Configuration at Startup

Configuration errors are cheapest to catch at boot. Spring Boot's `@ConfigurationProperties` integrates with Bean Validation, so you can fail fast when a required value is missing or malformed:

```java
@ConfigurationProperties(prefix = "storage")
@Validated
public class StorageProperties {

    @NotNull
    private String bucket;

    @Min(1)
    @Max(65535)
    private int port = 8080;

    @Valid
    private final S3 s3 = new S3();

    // getters and setters...

    public static class S3 {
        @NotBlank
        private String region;
        // getters and setters...
    }
}

With spring-boot-starter-validation on the classpath, an invalid storage.port or a blank storage.s3.region aborts startup with a clear BindValidationException rather than surfacing as a confusing NullPointerException deep in a request handler. This turns configuration into a contract: the application refuses to run in a misconfigured state.

Keeping Secrets Out of Configuration Files

Configuration files are checked into version control far more often than they should be. Treat anything sensitive—database passwords, API keys, signing secrets—as an external concern. The layered precedence model helps here: commit placeholder-free defaults, then inject real values through environment variables or a secrets manager at deploy time And that's really what it comes down to..

It's where a lot of people lose the thread.

# application.yml — safe to commit
spring:
  datasource:
    url: ${DB_URL:jdbc:postgresql://localhost:5432/app}
    username: ${DB_USER:app}
    password: ${DB_PASSWORD}

The ${DB_PASSWORD} placeholder with no default forces the value to be supplied externally; startup fails loudly if it is absent, which is exactly the behavior you want for a secret. For larger deployments, Spring Cloud Config or a vault integration can serve the same values through a PropertySource without ever writing them to disk Most people skip this — try not to..

Testing Configuration

Because configuration is just beans and bound properties, it is straightforward to test. A focused slice test can assert that a given set of properties produces the expected object graph:

@SpringBootTest(properties = {
    "storage.bucket=test-bucket",
    "storage.s3.
Out Now

Fresh Out

See Where It Goes

Interesting Nearby

Thank you for reading about Spring Boot Read Properties From Application Yml. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home