14 KiB
title, updated, created, source
| title | updated | created | source |
|---|---|---|---|
| Spring Boot 3 Template (Part 2) — Configuring application.yml | 2024-06-07 13:22:30Z | 2024-06-07 13:22:30Z | https://medium.com/@yohanesdwikiwitman/spring-boot-3-template-part-2-configuring-application-yml-d147b97c9d35 |
](https://medium.com/@yohanesdwikiwitman?source=post_page-----d147b97c9d35--------------------------------)
Photo by Ferenc Almasi on Unsplash
In Spring Boot 3, you can use both `application.yml` and `application.properties` as configuration files to specify application settings and properties. YAML is often considered more human-readable and less verbose than properties files. It uses indentation and a more structured format, which can make it easier to work with for complex configurations.
In a Spring Boot application, the `application.yml` (or `application.yaml`) file is typically located in the `src/main/resources` directory of your project. This directory is a common location for configuration files and resources in a Spring Boot application. Therefore, we will create this 3 files into spring project that we create earlier in Part 1 .
1. Rename your `application.properties` to `application.yml` and copy code below.
yaml: name: application.yml aliases: - properties.yml - env.yml
server: port: ${APP_PORT:9090} servlet: context-path: /theta compression: enabled: true min-response-size: 1024 forward-headers-strategy : framework
spring: banner: location: classpath:banner.txt profiles: active: ${PROFILE:local,dev} datasource: url: jdbc:mariadb://${DATABASE_HOST:localhost:3306}/${DATABASE_NAME:theta}?createDatabaseIfNotExist=true username: ${DATABASE_USER:root} password: ${DATABASE_PASSWORD:root} driver-class-name: org.mariadb.jdbc.Driver hikari: maximum-pool-size: ${HIKARI_POOL_SIZE:2} jpa: generate-ddl: false show-sql: true properties.hibernate.format_sql: true hibernate.ddl-auto: none flyway: enabled: true baselineOnMigrate: true validateOnMigrate: true locations: classpath:db/migration
management: endpoints: web: exposure: include: "*" endpoint: health: show-details: always
application: configuration: cors-allowed-list: - http://localhost:6555 - ${PORTAL_URL:http://localhost:8080} - ${API_URL:http://localhost:9090} public-api-list: - /api/public/**
logging: pattern: console: "%d{dd-MM-yyyy HH:mm:ss.SSS} %thread ${PID} [%X{correlationId}] %-5level %logger{36} - %class{1} - %msg%n"
Let’s break down the different sections of this YAML configuration:
1. `yaml` Section: — `name`: Specifies the name of the YAML configuration file, which is “application.yml.” — `aliases`: Specifies aliases for this configuration file, allowing it to be recognized by other names such as “properties.yml” and “env.yml.”
2. `server` Section: — `port`: Sets the server port that the application will listen on. It uses the environment variable `APP_PORT` if defined, otherwise, it defaults to port 9090. — `servlet`: Defines servlet-related configurations, such as the context path. — `compression`: Configures response compression settings, enabling compression for responses larger than 1024 bytes. — `forward-headers-strategy`: Configures how headers are forwarded, possibly related to reverse proxy setups.
3. `spring` Section: — `banner`: Specifies the location of a banner file to be displayed when the application starts. — `profiles`: Defines active profiles for the application. It uses the environment variable `PROFILE` if defined, defaulting to “local” and “dev” profiles. — `datasource`: Configures the database connection properties, including URL, username, password, and driver class. It uses default values if corresponding environment variables are not set. — `jpa`: Configures JPA (Java Persistence API) settings, such as SQL logging and Hibernate properties. — `flyway`: Configures Flyway database migration settings, enabling Flyway to manage database schema changes.
4. `management` Section: — `endpoints`: Configures access to management endpoints, allowing them to be exposed over the web. — `endpoint.health`: Configures health endpoint settings, including whether to show details.
5. `application` Section: — `configuration`: Contains application-specific configuration settings. — `cors-allowed-list`: Defines a list of allowed origins for Cross-Origin Resource Sharing (CORS) requests. — `public-api-list`: Specifies a list of public API paths.
6. `logging` Section: — `pattern`: Configures the logging pattern for console output, including timestamp, thread, process ID, correlation ID, log level, logger name, class name, and message format.
2. Create YamlPropertySourceFactory into factory package.
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource)
throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(encodedResource.getResource());
Properties properties = factory.getObject();
return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
}
}
The code above is for a custom `PropertySourceFactory` implementation in Spring Framework. It is used to create a custom property source that can read configuration properties from a YAML file and make them available to the Spring application’s environment.
Here’s a breakdown of the code:
1. The `YamlPropertySourceFactory` class implements the `PropertySourceFactory` interface, which is part of Spring Framework’s core configuration mechanism.
2. The `createPropertySource` method is overridden to provide custom logic for creating a property source from a YAML file.
3. Inside the `createPropertySource` method: — `String name`: This parameter represents the name of the property source (typically not used in this context). — `EncodedResource encodedResource`: This parameter represents the resource (in this case, a YAML file) from which properties should be loaded.
4. A `YamlPropertiesFactoryBean` is created. This factory bean is part of Spring Framework and is used to parse YAML files and convert them into a `Properties` object.
5. `factory.setResources(encodedResource.getResource())`: This line sets the resource (the YAML file) that should be parsed by the `YamlPropertiesFactoryBean`. The `encodedResource` parameter is used to obtain the resource.
6. `Properties properties = factory.getObject()`: This line retrieves the `Properties` object containing the properties parsed from the YAML file using the `YamlPropertiesFactoryBean`.
7. Finally, a new `PropertiesPropertySource` is created, using the name of the YAML file (obtained from `encodedResource.getResource().getFilename()`) as the property source name, and the `Properties` object as the source of properties.
3. Make YamlConfig under config package
@Configuration @EnableConfigurationProperties @ConfigurationProperties(prefix = "yaml") @PropertySource(value = "classpath:application.yml", factory = YamlPropertySourceFactory.class) public class YamlConfig { private String name; private List<String> aliases;
private List<String\> corsAllowedList = new ArrayList<>();
private List<String\> publicApiList = new ArrayList<>();
public List<String\> getCorsAllowedList() {
return corsAllowedList;
}
public void setCorsAllowedList(List<String\> corsAllowedList) {
this.corsAllowedList = corsAllowedList;
}
public List<String\> getPublicApiList() {
return publicApiList;
}
public void setPublicApiList(List<String\> publicApiList) {
this.publicApiList = publicApiList;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String\> getAliases() {
return aliases;
}
public void setAliases(List<String\> aliases) {
this.aliases = aliases;
}
@Override
public String toString() {
return "YamlConfig{" +
"name='" \+ name + '\\'' +
", aliases=" \+ aliases +
'}';
}
}
This code defines a Spring [@Configuration](http://twitter.com/Configuration) class called `YamlConfig`, which is used to read and bind properties from a YAML configuration file (`application.yml`) to Java objects. Let’s break down the code step by step:
1. [@Configuration](http://twitter.com/Configuration): This annotation indicates that the class is a Spring configuration class, allowing it to define beans and configuration settings.
2. [@EnableConfigurationP](http://twitter.com/EnableConfigurationP)roperties: This annotation is used to enable the processing of [@ConfigurationPropert](http://twitter.com/ConfigurationPropert)ies beans. It allows Spring to scan for classes annotated with [@ConfigurationPropert](http://twitter.com/ConfigurationPropert)ies and bind properties from configuration files to those classes.
3. [@ConfigurationPropert](http://twitter.com/ConfigurationPropert)ies(prefix = “yaml”): This annotation is used to specify that this class should be used for binding properties with a specific prefix in the configuration file. In this case, it binds properties with the prefix “yaml.”
4. [@PropertySource](http://twitter.com/PropertySource)(value = “classpath:application.yml”, factory = YamlPropertySourceFactory.class): This annotation is used to specify the source of the properties. It indicates that properties should be loaded from the “classpath:application.yml” file, and it specifies the custom property source factory `YamlPropertySourceFactory.class` to read YAML files.
5. Inside the `YamlConfig` class, you have several private fields that correspond to properties in the YAML file: — `private String name`: Represents the “name” property in the YAML file. — `private List<String> aliases`: Represents the “aliases” property in the YAML file. — `private List<String> corsAllowedList`: Represents the “cors-allowed-list” property in the YAML file. This property has a default value of an empty list. — `private List<String> publicApiList`: Represents the “public-api-list” property in the YAML file. This property also has a default value of an empty list.
6. The class provides getter and setter methods for each of these fields, allowing Spring to set their values based on the properties defined in the YAML configuration file.
7. The `toString()` method is overridden to provide a human-readable representation of the `YamlConfig` object, showing the values of the fields.
4. Modify ThetaApplication as main application
@SpringBootApplication public class ThetaApplication implements CommandLineRunner {
@Autowired private YamlConfig yamlConfig;
public static void main(String[] args) { SpringApplication.run(ThetaApplication.class, args); }
@Override public void run(String... args) throws Exception { System.out.println("YAML Properties " + yamlConfig.toString()); } }
This code represents the main application class for a Spring Boot application named `ThetaApplication`. Let’s break down what this class does:
1. [@SpringBootApplicatio](http://twitter.com/SpringBootApplicatio)n: This annotation is used to indicate that this class is the main entry point of a Spring Boot application. It combines three annotations: [@Configuration](http://twitter.com/Configuration), [@EnableAutoConfigurat](http://twitter.com/EnableAutoConfigurat)ion, and [@ComponentScan](http://twitter.com/ComponentScan). It tells Spring Boot to enable component scanning to discover beans, configure the application, and automatically configure various settings based on classpath dependencies.
2. `public static void main(String[] args)`: This is the main method of the application. It is the entry point for starting the Spring Boot application. When you execute this class, it will run the Spring Boot application, which initializes the Spring context and starts the application.
3. `SpringApplication.run(ThetaApplication.class, args)`: This line of code runs the Spring Boot application. It takes two arguments: — `ThetaApplication.class`: The main application class that contains the configuration and behavior of the Spring Boot application. — `args`: Command-line arguments passed to the application.
4. `implements CommandLineRunner`: This class implements the `CommandLineRunner` interface. This interface provides a callback method `run(String… args)` that is executed after the Spring Boot application context is fully initialized but before it starts serving HTTP requests.
5. [@Autowired](http://twitter.com/Autowired) private YamlConfig yamlConfig;: This annotation injects an instance of the `YamlConfig` class into the `ThetaApplication` class. `YamlConfig` is a custom configuration class that is configured to read properties from the “application.yml” file.
6. `run(String… args)`: This method is the implementation of the `CommandLineRunner` interface. It will be executed when the application starts. In this method, it simply prints the content of the `yamlConfig` bean to the console using `System.out.println()`. This allows you to see the values of properties defined in the “application.yml” file.
When running the application, it will display the YAML configuration you are using.

