Home > Back-end >  How to convert few yaml properties to class in spring boot
How to convert few yaml properties to class in spring boot

Time:07-21

I have following application-yml.

server:
  port: 9090

spring:
   application:
      name: employee-management

employee:
   details:
     firstname: John
     lastname: DK

     firstname: Henry
     lastname: K

     firstname: Sofiya
     lastname: H

And my Java class

@Builder
@AllArgsConstructor
@NoArgsConstructor
@Configuration
@ConfigurationProperties(prefix = "employee")
public class Employee{
  public List<Name> details;
}

But along with employee properties, it's also reading other spring properties.

Yaml yaml = new Yaml();
    InputStream inputStream = class.getClassLoader().getResourceAsStream("application.yml),
    Employee obj = yaml.loadAs(inputStream, Employee.class);

I am getting this following error.

Cannot create property=server for JavaBean=com.example.common.util.Employee@7d365620
 in 'reader', line 1, column 1:
    server:
    ^
Unable to find property 'server' on class: com.example.common.util.Employee
 in 'reader', line 2, column 3:
      port: 9090

How can I avoid other spring properties while reading the resource file? Thanks in Advance!

CodePudding user response:

you could do:

    Yaml yaml = new Yaml();
    InputStream inputStream = getResourceAsStream("application.yml");
    Map<String, Object> properties = yaml.loadAs(inputStream, Map.class);

    final ObjectMapper mapper = new ObjectMapper();
    final Employee obj = mapper.convertValue(properties.get("employee"), Employee.class);

this basically creates a map of all properties, gets just the employee props and builds the Employee instance from that.

  • Related