springspring-bootjava-record

Mapping values from application.yml to Java record class but value is null


My spring boot version is implementation("org.springframework.boot:spring-boot-starter-web:3.1.2").

In application.yml I have defined those properties:

machine:
  product:
    port: 6443
    location:
      foo: "loc-1"
      bar: "loc-2"

I would like to create a record to associate with these properties, so I tried:

@ConfigurationProperties(prefix = "machine")
public record MachineProperties(Product productProperties) {
    public record Product(Location locationProperties) {
        public record Location(String foo, String bar) {

        }
    }
}

I inject the above class to another one:

@Component
public class Other {
  private final MachineProperties machineProperties;

    @Autowired
    public Other(MachineProperties machineProperties) {
        this.machineProperties = machineProperties;
    }
}

But at runtime, the breakpoint shows me productProperties inside machineProperties is null. Why is that? What am I missing?


Solution

  • There is a problem with naming fields in the MachineProperties record class.

    If you want to use properties named product and location, the fields must have the same name.

    The following code works well:

    @ConfigurationProperties(prefix = "machine")
    public record MachineProperties(Product product) {
        public record Product(Location location) {
            public record Location(String foo, String bar) {
    
            }
        }
    }
    

    From the naming point of view, I think using productProperties and locationProperties inside a property container that already has "properties" in its name is overkill. So you just need to rename these fields.