How to get boolean value from application.yml in SpringBoot

Viewed 872

I have application.yml that looks like this:

feature:
  toggles:
    checksLoginAndRegistration: true

I am trying to get it in my class with @Value annotation, but it's not working.

public class UMLUserRepository implements UserRepository {

    @Value("${feature.toggles.checksLoginAndRegistration}")
    private boolean checksLoginAndRegistration;

        private void validateLoginNow(LoginInfo info, User user) {
        checkKnownBlock(info, user.username);
        if(checksLoginAndRegistration){
            try {
                service.validateLogin(user.username);
            } catch (ValidationException alidationException) {
                throw new Exception(user.username);
            }
        }
    }

When I debug the code my checksLoginAndRegistration variable is set to false.

2 Answers

According to the comments you have used @Value annotation within a simple POJO. Not inside a Spring Bean like @Component, @Service or @Configuration.

You cannot inject a value to a POJO class using @Value.

This annotation can be used for injecting values into fields in Spring-managed beans, and it can be applied at the field or constructor/method parameter level.

But still you get value false for checksLoginAndRegistration parameter because it is an primitive type which has a default value false. If you chaged it to boxed type Boolean you can see the value of checksLoginAndRegistration is null

Update

@ConfigurationProperties(prefix = "feature.toggles")
public class AppConfig {
    private Boolean checksLoginAndRegistration;
}

Then update your UMLUserRepository class, (We make checksLoginAndRegistration is a dependency to UMLUserRepository class)

public class UMLUserRepository implements UserRepository {
    private final Boolean checksLoginAndRegistration;
 
    public UMLUserRepository(Boolean checksLoginAndRegistration) {
        this.checksLoginAndRegistration = checksLoginAndRegistration;
    }
}

This is the class where you crate instance of UMLUserRepository class. An it should be a Spring Bean.

@Component (or @Service)
public class ClassYouInitatingUMLUserRepository {

    @Autowire
    private AppConfig appConfig;

    public void yourMethod() {
        UMLUserRepository repo = new UMLUserRepository(appConfig.getChecksLoginAndRegistration());
    }

I would encourage you to check the possibility to convert UMLUserRepository class to a Spring bean. Then this won't be needed.

Hmm, it seems like you do everything correctly. I can suggest what can go wrong

  • Is it all what file contains?

If not, check is there only one feature key or not. If there's another one, remove it.

  • Have you added @Configuration annotation to your configuration class?

If not, add it.

Related