user1555190
user1555190

Reputation: 3239

spring populating configuration properties, am unable to do so

i so im trying to populate a configuration class with a boolean value and i keep getting the below

Parameter 0 of constructor in example.demo.config required a bean of type 'java.lang.Boolean' that could not be found.

classes:

@EnableFeignClients
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

@Configuration
@ConfigurationProperties
@Builder
@Getter
@Setter
public class config {

    @Value("${enabled}")
    private Boolean enabled;

    @Value("#$'{values}'.split(',')")
    private List<String> values;

application.properties

enabled=true
values=3,4,5,6,7

Upvotes: -1

Views: 167

Answers (1)

Dirk Deyne
Dirk Deyne

Reputation: 6936

There are several options:

  • Remove @Builder from the config-class. Because @Builder forces an all-argument constructor and Spring, using @Value, needs a no-argument constructor.

  • Use @Value in the constructor.


@Configuration
@Builder
@Getter
@Setter
class Config {

    private Boolean enabled;

    private List<String> values;

    public Config(@Value("${enabled}") Boolean enabled, @Value("${values}") List<String> values) {
        this.enabled = enabled;
        this.values = values;
    }
}

Note that spring is smart enough to convert 3,4,5,6,7 to a list of numbers/strings

Looking back at option one... there is actually a third option:

@Configuration
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
class Config {
    @Value("${enabled}")
    private Boolean enabled;
    @Value("${values}")
    private List<String> values;

}

And for completeness, without @Value

  1. @EnableConfigurationProperties({Config.class})
  2. @ConfigurationProperties(prefix = "prefix"), prefix can be empty
  3. @ConstructorBinding tell spring to use constructor binder
@SpringBootApplication
@EnableConfigurationProperties({Config.class}) // <-- 1
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

@ConfigurationProperties(prefix = "prefix") // <-- 2
@ConstructorBinding // <-- 3
@Builder
@Getter
@Setter
class Config {

    private Boolean enabled;

    private List<String> values;

}

Upvotes: 1

Related Questions