cocaColaPha
cocaColaPha

Reputation: 43

How to read from application.yml file in Java

I wrote an e mail program. But I had to change the some configs, so in my project I need to know how to read from yaml for my loginUrl

my code below;

  userNotificationEmail.setIsActive("F");
  userNotificationEmailRepository.save(userNotificationEmail);
  activationResultType.setResultCode(ActivationResultCode.SUCCESSFUL);
  activationResultType.setUser(userMapper.fromUser(userEntity));
  activationResultType.setLoginUrl(loginUrl);
  return activationResultType;

Upvotes: 4

Views: 26263

Answers (3)

Ganeshan NT
Ganeshan NT

Reputation: 11

you can use @Value like below in your class to inject the value.

@Value("${property.name}") 
String propertyValue;

Still you aren't able to access value... consider below cases as well.

YML file:

authorization:
  server:
    baseUri: 'http://localhost:9090/'

use @Value("${authorization.server.base-uri}") instead of @Value("${authorization.server.baseUri}") to get YML value inside controller.

Key point to note here as per spring documentation

If you do want to use @Value, we recommend that you refer to property names using their canonical form (kebab-case using only lowercase letters). This will allow Spring Boot to use the same logic as it does when relaxed binding @ConfigurationProperties. For example, @Value("{demo.item-price}") will pick up demo.item-price and demo.itemPrice forms from the application.properties file, as well as DEMO_ITEMPRICE from the system environment. If you used @Value("{demo.itemPrice}") instead, demo.item-price and DEMO_ITEMPRICE would not be considered.

Upvotes: 1

Vitor Gabriel Carrilho
Vitor Gabriel Carrilho

Reputation: 365

You can inject in your class with:

@Value("${propertie.name}") 
String value;

Upvotes: 0

Thoomas
Thoomas

Reputation: 2408

If your key is loginUrl (inside your yaml file), you can inject its value with the @Value annotation, inside a Spring component.

@Value("${loginUrl}")
private String loginUrl;

If it's a second level property, the path is @Value("${yourFirstKey.loginUrl}").

More documentation about reading YAML files with Spring Boot.

Upvotes: 7

Related Questions