Home > other >  Spring boot yaml property boolean not recognized
Spring boot yaml property boolean not recognized

Time:10-02

I have the following in application.yml:

perscel:
  mail:
    featuretoggle: true

Following field:

@Value("${perscel.mail.featuretoggle}")
private final Boolean isFeatureActive;

results in:

Parameter 7 of constructor in be.cm.apps.press.perscel3.cron.CronJob required a bean of type 'java.lang.Boolean' that could not be found.

A bit annoyed by the unexpected issue, clearly the boolean field is set to true.
Note that all other fields under the same namespaces are properly filled in, it is literally only the boolean field that is causing the problem.
I have no additional configuration for reading properties files.

Spring boot starter xparent version 2.4.2

Edit: The AllArgsConstructor is annotated by lombok.
I have the following properties:

@Value("${perscel.mail.featuretoggle}")
private final Boolean isFeatureActive;

@Value("#{'${perscel.mail.recipients.developers}'.split(',')}")
private final List<String> emailRecipientsDevelopers;

@Value("#{'${perscel.mail.recipients.admins}'.split(',')}")
private final List<String> emailRecipientsAdmins;

The two lists properly worked, I only have a problem after adding the boolean value.

CodePudding user response:

Note that Spring complains on the constructor, not on the field annotation. So, this is basically because of missing @Value annotation on the constructor param in auto-generated code by Lombok.

You basically have 2 options:

  1. Remove @AllArgsConstructor (and final field modifier), mark all the bean fields with @Autowired and let Spring set fields for you directly instead of using constructor.
  2. Add constructor with all the arguments explicitly, not relying on Lombok auto-generated one. But this time - place @Value annotation on the corresponding constructor param.

CodePudding user response:

The issue is you are marked all the @Value fields as final. Then what happens is Lombok will add those field to the constructor because you have annotated with @AllArgsConstructor.

When Spring initialize this bean, Spring assumes the all the filed in the constructor are Spring managed beans and Spring try to autowire them to this bean.

The easy fix is remove all the final word from those fields and remove @AllArgsConstructor. Removing @AllArgsConstructor always safe unless you are completely aware what is actually doing inside a Spring bean.

  • Related