5

If a bean class comes from an external library (eg my own commons library), how can I populate that bean using @ConfigurationProperties?

Example: from a commons library:

package com.my.commons.person;

import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotNull;

@Validated
public class CommonPerson {
    private @NotNull String name;
    private @NotNull String age;

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getAge() { return age; }
    public void setAge(String age) { this.age = age; }
}

Implementation project:

package com.my.api;

@SpringBootApplication
public class MainApp extends SpringBootServletInitializer {
    @Bean
    @ConfigurationProperties("commons.person")
    public CommonPerson person() {
        return new CommonPerson();
    }
}

application.properties (also only in the implementation project):

commons.person.name=Dummy
commons.person.age=30

Result:

application startup fails due to validation exception. o.s.b.b.PropertiesConfigurationFactory : Field error in object 'commons.person' on field 'name': rejected value [null]...

By the way: if I move the CommonPerson directly into the implementation project, the code works as expected. It just only does not work if the class is coming from external...

According to the docs this should work though: @ConfigurationProperties on thirdparty classes

I'm loading my commons package with maven:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/>
</parent>
<dependencies>
    <dependency>
        <groupId>com.my.commons</groupId>
        <artifactId>person-commons</artifactId>
        <version>1.0.0</version>
    </dependency>
</dependencies>
membersound
  • 81,582
  • 193
  • 585
  • 1,120

2 Answers2

0

As pointed out by @davidxxx and the others, the code itself is correct.

The problem in my case might have been some caching issue from the IDE. I just took out the commons library in the pom.xml, saved it, and read it. That somehow triggered a cleanup inside the IDE that a mvn clean install did not (as I ran those maven goals several times before).

Ali Ben Zarrouk
  • 1,891
  • 16
  • 24
membersound
  • 81,582
  • 193
  • 585
  • 1,120
0

Try to enable configuration properties support with... @EnableConfigurationProperties annotation, it may help.

Some examples and explanation of usage: 1 and 2

staszko032
  • 802
  • 6
  • 16