简体   繁体   中英

Read complex values from properties.yml file in spring boot application

spring:
  profiles:
    active: dev
  data:
    mongodb:
      uri: mongodb://127.0.1:27017/FeteBird-Product
  kafka:
    bootstrapAddress: localhost:9092
    producer:
      key-serializer: org.springframework.kafka.support.serializer.JsonSerializer
      value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
    consumer:
      key-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
      value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
      auto-offset-reset: earliest
      properties:
        spring:
          json:
            trusted:
              packages: '*'

How can I read all the values in spring boot, I know I can read by configuration as below

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties("demo")
public class Config {}

I don't know how to create a properties and access in other classes.

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "spring")
public class ApplicationYmlConfiguration {
    private KafkaConfigurationYml kafka;

    public KafkaConfigurationYml getKafka() {
        return kafka;
    }

    public void setKafka(KafkaConfigurationYml kafka) {
        this.kafka = kafka;
    }
}


public class KafkaConfigurationYml {
    private String bootstrapAddress;

    public String getBootstrapAddress() {
        return bootstrapAddress;
    }

    public void setBootstrapAddress(String bootstrapAddress) {
        this.bootstrapAddress = bootstrapAddress;
    }
}

Read it anywhere

@Configuration
public class KafkaConfiguration {
    private ApplicationYmlConfiguration bootstrapAddress;

    public KafkaConfiguration(ApplicationYmlConfiguration bootstrapAddress) {
        this.bootstrapAddress = bootstrapAddress;
    }}

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