Skip to content
Advertisement

Is it known you shouldn’t name methods starting with ‘get’ when using @ConfigurationProperties on a Spring @Component

Suppose a simple Spring Boot @Component like this one:

    @Component
    @Data
    @EnableScheduling
    @ConfigurationProperties(prefix = "demo")
    public class DemoClass {

        private String aString;
        private Long aLong;

        @Scheduled(fixedDelayString = "${demo.delay}")
        void getSomething() {
            System.out.println("aString = " + aString);
            System.out.println("aLong = " + aLong.toString());
        }
    }

It will not start throwing

ConfigurationPropertiesBindException: Error creating bean with name ‘demoClass’: Could not bind properties to ‘DemoClass’

All you need to fix is a getSomething method name. Just rename it to putSomething for example. I’ve lost three hours debugging Spring Boot sources and found it: Spring tries to bind Bean property named Something. And the exception occurs.

I know it’s a weird practice to name methods starting with get if it’s not a getter, but is it mentioned somewhere in Spring Docs? Does it say something about guessing properties names from method names?

Advertisement

Answer

Yes Spring uses the JavaBeans standard to process the configuration properties POJO, as explained here:

Such arrangement relies on a default empty constructor and getters and setters are usually mandatory, since binding is through standard Java Beans property descriptors, just like in Spring MVC.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement