springBoot中有分别提供了两个注解来读取配置文件,分别是@Value(“${}”)与@ConfigurationProperties(prefix = ""),下面分别讲述两种在不同情况下的用法。
yml文件格式:
service:
elasticsearch:
url: llllllllllllllll
username: 222222222222
password: 4444444444444
kafka:
bootstrap-servers: 444444444444
consumer:
auto-offset-reset: latest
max-poll-records: 3100
enable-auto-commit: false
auto-commit-interval: 1000
session-timeout: 20000
listener:
batch-listener: true
concurrencys: 5,10
poll-timeout: 1500
第一种方式使用 @ConfigurationProperties(prefix = "")来进行读取:
package com.example.demo.example.text;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @title: readConfigs
* @Author linzm
* @Date: 2022/8/17 13:23
* @Version 1.0
*/
@Component(value = "readConfigs")
@ConfigurationProperties(prefix = "service")
@Data
public class readConfigs {
@Autowired
Elasticsearch elasticsearch;
@Autowired
Kafka kafka;
/**
* 使用内部类来解决yml多层结构
*/
@Data
@Component
@ConfigurationProperties(prefix = "service.elasticsearch")
public static class Elasticsearch{
private String url;
private String username;
private String password;
}
@Data
@Component
@ConfigurationProperties(prefix = "service.kafka")
public static class Kafka{
@Autowired
Consumer consumer;
@Autowired
Listener listener;
private String bootstrapServers;
}
@Data
@Component
@ConfigurationProperties(prefix = "service.kafka.consumer")
public static class Consumer{
private String autoOffsetReset;
private String maxPollRecords;
private String enableAutoCommit;
private String autoCommitInterval;
private String sessionTimeout;
}
@Data
@Component
@ConfigurationProperties(prefix = "service.kafka.listener")
public static class Listener{
private String batchListener;
private String concurrencys;
private String pollTimeout;
}
}
测试:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(DemoApplication.class, args);
readConfigs readConfigs = (readConfigs) run.getBean("readConfigs");
String autoCommitInterval = readConfigs.getKafka().getConsumer().getAutoCommitInterval();
System.out.println(autoCommitInterval);
System.out.println("启动成功.....");
}
}
以上就很成功的拿到了值。这样是不是看起来高大上了一点。
第一种方式使用 @Value(“${}”)来进行读取:
package com.example.demo.example.text;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @title: ReadConfiga
* @Author linzm
* @Date: 2022/8/17 14:01
* @Version 1.0
*/
@Component(value = "readConfiga")
@Data
public class ReadConfiga {
@Value("${service.elasticsearch.url:100}")
private String elasticsearch;
}
@Value(“${}”)要注意的是最好加个默认值,以防报错(:默认值);