Java application properties yaml

Spring Boot Application Properties and YAML

In a typical Maven project setup, the application.properites or application.yml files live within the /src/main/resources folder of your application’s project structure.

Application Properties File

some.property.here=Spring Properties File 

Application YAML File

some: property: here: Spring YAML File 

You can then inject properties into your Spring Boot application’s java code by using the @Value annotation:

import org.springframework.beans.factory.annotation.*; @Component Public class MyAppBean  @Value("$") private String myDynamicVariable; > 

Depending on which application properties or YML file that is loaded, the value of myDynamicVariable will differ. This is incredibly useful for variables that are environment dependent or ones that can change based on the active Spring Profile.

Application Properties and YAML Profiles

Depending on the Maven or Spring Boot profile you are using, you can have different application.properties or application.yml files which represent configurations for the respective environment.

  • Use a application-dev.properties file which would be used if your application is running in a development environment.
  • Use a production specific application-prod.properties which is used when running your application within production.

The appended dev or prod keys match the Spring profile which is currently active.

Combining, Overriding, and Inheritance in Properties

What happens when you have properties or definitions that remain the same across different profiles?

Conveniently, Spring has built in a configuration inheritance in which values can be defined in one file and superseded or override one or more times in further property files.

For example, say I define a property my.favorite.color=blue within my application.properties file. If no Spring profile is configured, the value will remain set to blue. Should one define a dev profile, you could have your application-dev.properties overwrite this and set it to red.

You can define multiple Spring profiles by chaining them in the order you want them to override one another:

mvn spring-boot:run -Dspring.profiles.active=dev,prod 

In this situation, any values defined in dev that are also defined within the prod file would be overwritten, because prod is defined after dev.

You can mix application.properties files with application.yml files too! These YAML files follow the aforementioned pattern of inheritance and profiling. You can have an application.yml and an application-dev.yml file that overrides specific values for a dev centric environment.

YAML vs Properties files

By default, Spring Boot applications support YAML as an alternative to properties files if you are using any of the spring-boot-starter dependencies. If you wish to use YAML documents to inject configuration data into your Spring Boot application, you will need to ensure that they align correctly to match the hierarchy of a property file. For example:

server: port: 8080 servlet: context-path: / logging: level: root: DEBUG org.springframework.web: DEBUG myapp: domain-list: - something.com - example.net 

The above would translate to the following properties file:

server.port=8080 server.servlet.context-path=/ logging.level.root=DEBUG logging.level.org.springframework.web=DEBUG myapp.domain-list[0]=something.com myapp.domain-list[1]=example.net 

External application properties and yml files

Should you have properties or yaml files external to your project file or directory, you can include them by adding the following parameter when invoking your Spring Boot application:

mvn spring-boot:run -Dspring.config.location="file://path/to/application.properties" 

Alternatively you can specify a path to your YAML or properties in an environment variable like so:

# Loads application.properties and application.yml files # (including files appended with your Spring environment such as # application-dev.properties or application-prod.yml) export SPRING_CONFIG_NAME=application export SPRING_CONFIG_LOCATION=file://path/to/config/folder/ java -jar SpringBootApplication.jar 

Note that the environment variables are using underscores instead of periods to separate the key names. Knowing this pattern, you can include other properties in this same manner.

Finally, you can load properties files via a properties file (or YAML for that matter), by adding a line like so in your application.properties: (this feature is new to Spring Boot 2.4)

spring.config.import=file:./supplementary.yml,optional:file:./anotherfile.properties 

You can also include entire folders via the filesystem or classpath or using wildcards :

spring.config.import=optional:classpath:/config/*/ 
spring.config.import=optional:file:/config/*/ 

Notice the optional: prefix? That tells Spring not to worry if the referenced properties file cannot be found, and to keep on bootstrapping.

Spring Articles

See more of my articles on Spring:

  • Spring4Shell remediation guide
  • Spring JdbcAggregateTemplate Example
  • Spring JDBC BeforeSaveCallback Example
  • Spring AsyncRestTemplate is now Deprecated
  • Forwarded Headers Example in Spring
  • Spring Milestone and Snapshot Maven Repositories
  • IntelliJ Spring Boot Starter Not Found Error
  • Spring Cloud Function Example for AWS Lambdas
  • SpringBootRequestHandler is now Deprecated
  • Spring Native Application Example
  • Spring Security 5 OAuth2 OIDC Example
  • Spring Boot Starter Parent Example
  • R2DBC Reactive Database Example in Spring
  • Synchronized ItemStreamWriter example in Spring Batch 4.3
  • JdbcTemplate queryForStream Example Spring 5.3
  • spring-security-saml2-service-provider example
  • ORA-01000: Oracle maximum open cursors exceeded in Spring Boot
  • Spring Boot Starters
  • Spring Boot SAML2 — How to skip the select an identity provider page
  • Spring Boot Package Scanning Configuration

Источник

Использование application.yml и application.properties в Spring Boot

Распространенной практикой в Spring Boot является использование внешней конфигурации для определения наших свойств . Это позволяет нам использовать один и тот же код приложения в разных средах.

Мы можем использовать файлы свойств, файлы YAML, переменные среды и аргументы командной строки.

В этом кратком руководстве мы рассмотрим основные различия между свойствами и файлами YAML.

2. Конфигурация свойств​

По умолчанию Spring Boot может получить доступ к конфигурациям, установленным в файле application.properties , который использует формат ключ-значение:

 spring.datasource.url=jdbc:h2:dev spring.datasource.username=SA  spring.datasource.password=password 

Здесь каждая строка представляет собой одну конфигурацию, поэтому нам нужно выразить иерархические данные, используя одни и те же префиксы для наших ключей. И в этом примере каждый ключ принадлежит spring.datasource .

2.1. Заполнители в свойствах​

Внутри наших значений мы можем использовать заполнители с синтаксисом $<> для ссылки на содержимое других ключей, системных свойств или переменных среды:

 app.name=MyApp  app.description=$app.name> is a Spring Boot application 

2.2. Структура списка​

Если у нас есть одинаковые свойства с разными значениями, мы можем представить структуру списка с индексами массива:

 application.servers[0].ip=127.0.0.1  application.servers[0].path=/path1 application.servers[1].ip=127.0.0.2  application.servers[1].path=/path2 application.servers[2].ip=127.0.0.3  application.servers[2].path=/path3 

2.3. Несколько профилей​

Начиная с версии 2.4.0, Spring Boot поддерживает создание файлов свойств, состоящих из нескольких документов. Проще говоря, мы можем разделить один физический файл на несколько логических документов.

Это позволяет нам определить документ для каждого профиля, который нам нужно объявить, в одном и том же файле:

logging.file.name=myapplication.log bael.property=defaultValue #--- spring.config.activate.on-profile=dev spring.datasource.password=password spring.datasource.url=jdbc:h2:dev spring.datasource.username=SA bael.property=devValue #--- spring.config.activate.on-profile=prod spring.datasource.password=password spring.datasource.url=jdbc:h2:prod spring.datasource.username=prodUser bael.property=prodValue 

Обратите внимание, что мы используем нотацию ‘#—‘, чтобы указать, где мы хотим разделить документ.

В этом примере у нас есть две пружинные секции с разными профилями . Также у нас может быть общий набор свойств на корневом уровне — в этом случае свойство logging.file.name будет одинаковым во всех профилях.

2.4. Профили в нескольких файлах​

В качестве альтернативы использованию разных профилей в одном файле мы можем хранить несколько профилей в разных файлах. До версии 2.4.0 это был единственный метод, доступный для файлов свойств .

Этого мы добиваемся, помещая имя профиля в имя файла — например, application-dev.yml или application-dev.properties .

3. Конфигурация YAML​

3.1. YAML-формат​

Помимо файлов свойств Java, мы также можем использовать файлы конфигурации на основе YAML в нашем приложении Spring Boot. YAML — это удобный формат для указания иерархических данных конфигурации.

Теперь давайте возьмем тот же пример из нашего файла свойств и преобразуем его в YAML:

 spring:   datasource:   password: password  url: jdbc:h2:dev  username: SA 

Это может быть более удобочитаемым, чем альтернативный файл свойств, поскольку он не содержит повторяющихся префиксов.

3.2. Структура списка​

YAML имеет более краткий формат для выражения списков:

 application:   servers:   - ip: '127.0.0.1'  path: '/path1'   - ip: '127.0.0.2'  path: '/path2'   - ip: '127.0.0.3'  path: '/path3' 

3.3. Несколько профилей​

В отличие от файлов свойств, YAML изначально поддерживает файлы с несколькими документами, и таким образом мы можем хранить несколько профилей в одном файле независимо от того, какую версию Spring Boot мы используем.

Однако в этом случае спецификация указывает, что мы должны использовать три дефиса для обозначения начала нового документа :

logging:  file:  name: myapplication.log --- spring:  config:  activate:  on-profile: staging  datasource:  password: 'password'  url: jdbc:h2:staging  username: SA bael:  property: stagingValue 

Примечание. Обычно мы не хотим одновременно включать в наш проект стандартные файлы application.properties и application.yml , так как это может привести к неожиданным результатам.

Например, если мы объединим показанные выше свойства (в файле application.yml ) со свойствами, описанными в разделе 2.3., тогда bael.property будет присвоено значение по умолчанию, а не значение, зависящее от профиля. Это просто потому, что application.properties загружаются позже, переопределяя значения, назначенные до этого момента.

4. Использование Spring Boot​

Теперь, когда мы определили наши конфигурации, давайте посмотрим, как получить к ним доступ.

4.1. Аннотация значения ​

Мы можем внедрить значения наших свойств, используя аннотацию @Value :

 @Value("$")   private String injectedProperty; 

Здесь свойство key.something вводится через внедрение поля в один из наших объектов.

4.2. Абстракция среды ​

Мы также можем получить значение свойства с помощью Environment API:

 @Autowired   private Environment env;    public String getSomeKey()   return env.getProperty("key.something");   > 

4.3. Аннотация свойств конфигурации ​

Наконец, мы также можем использовать аннотацию @ConfigurationProperties для привязки наших свойств к типобезопасным структурированным объектам:

 @ConfigurationProperties(prefix = "mail")   public class ConfigProperties    String name;   String description;   ... 

5. Вывод​

В этой статье мы увидели некоторые различия между свойствами и файлами конфигурации yml Spring Boot. Мы также увидели, как их значения могут ссылаться на другие свойства. Наконец, мы рассмотрели, как внедрить значения в нашу среду выполнения.

Как всегда, все примеры кода доступны на GitHub .

Оцените статью