Own configuration properties

36 views Asked by At

Following chapter 5 of Spring in action fifth edition I have tried to establish my own confuguration variables with spring boot:

@Component
@ConfigurationProperties(prefix = "myprops")
public class MyClass {

    private int myvar1;

    // Getters and setters...
}

Written in file application.properties only this:

myprops.myvar1=3333

MyClass.getMyvar1() should return 3333 now but it still returns the default int value: 0.

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

    @Bean
    public CommandLineRunner foo(ApplicationContext ctx) {
        return args -> {
            MyClass mc = new MyClass();
            int x = mc.getMyvar1();
            System.out.println(x);
        };
    }
}
1

There are 1 answers

0
Ori Marko On

Add @EnableConfigurationProperties(MyClass.class) to Demo1Application

If we don’t use @Configuration in the POJO, then we need to add @EnableConfigurationProperties(ConfigProperties.class) in the main Spring application class to bind the properties into the POJO: