简体   繁体   中英

How to convert few yaml properties to class in spring boot

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM