SpringBoot 读取配置文件

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-configuration-processor</artifactId>
  <optional>true</optional>
</dependency>
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
</dependency>

默认配置文件

application.properties / application.yml

一、参数

app.name = yuque
app.web-url = https://www.csdn.com
app.cron = 0/10 * * * * ?
app:
  name: yuque
  web-url: https://www.csdn.com
  # 每两天执行一次
  cron: 0 0 0 */2 * ?

1. 直接获取

注解上可直接获取,其他地方需要使用 @Value 获取

@Value("${app.web-url}")
private String url;

@KafkaListener(topics = "${app.name}")
public void onMessage() {
    System.out.print("地址信息:" + url);
}

@Scheduled(cron = "${app.cron}")
public void test() {}

2. 使用 @Value 注解

在当前类使用

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(classes = Application.class)
@RunWith(SpringRunner.class)
public class ApplicationTest {
    
    @Value("${app.name}")
    private String name;
    
    @Value("${app.web-url}")
    private String webUrl;
    
    @Test
    public void test() {
        System.out.println(name);
        System.out.println(webUrl);
    }
}

3. 使用 @ConfigurationProperties 注解

采用自动配置的方式映射配置文件属性,配置完成后直接当做 java 对象即可使用

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;


/**
 * - @ConfigurationProperties(value = "app") 表示的配置文件里属性的前缀都是 app 开头
 * - 文件映射规则,短横线(-)驼峰式命名
 */
@Data
@Component
@ConfigurationProperties(value = "app")
public class AppProperties {
     
    private String name;    
    private String webUrl;
}

4. 测试类

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(classes = Application.class)
@RunWith(SpringRunner.class)
public class ApplicationTest {

    @Autowired
    private AppProperties appProperties;

    @Test
    public void test() {
        System.out.println(appProperties.getName());
        System.out.println(appProperties.getWebUrl());
    }
}

二、对象

app.test-user.name = cnbai
app.test-user.address = xian
app:
  test-user:
    address: xian
    name: cnbai

1. 使用 @Value 注解

在当前类使用

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(classes = Application.class)
@RunWith(SpringRunner.class)
public class ApplicationTest {
    
    @Value("${app.test-user.name}")
    private String username;
    
    @Value("${app.test-user.address}")
    private String address;
    
    @Test
    public void test() {
        System.out.println(username);
        System.out.println(address);
    }
}

2. 使用 @ConfigurationProperties 注解

采用自动配置的方式映射配置文件属性,配置完成后直接当做 java 对象即可使用

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(value = "app")
public class AppProperties {
     
    private TestUser testUser;
    
    @Data
    public static class TestUser {
        private String name;
        private String address;
    }
}

3. 测试类

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(classes = Application.class)
@RunWith(SpringRunner.class)
public class ApplicationTest {

    @Autowired
    private AppProperties appProperties;

    @Test
    public void test() {
        System.out.println(appProperties.getTestUser().getName());
        System.out.println(appProperties.getTestUser().getAddress());
    }
}

三、数组

app.name = zhangsan,lisi
app:
  name: zhangsan,lisi

1. 使用 @Value 注解

在当前类使用

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(classes = Application.class)
@RunWith(SpringRunner.class)
public class ApplicationTest {
    
    @Value("${app.name}")
    private String[] name;
    
    @Test
    public void test() {
        System.out.println(name);
    }
}

2. 使用 @ConfigurationProperties 注解

采用自动配置的方式映射配置文件属性,配置完成后直接当做 java 对象即可使用

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(value = "app")
public class AppProperties {
    
    private String[] name;
}

3. 测试类

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(classes = Application.class)
@RunWith(SpringRunner.class)
public class ApplicationTest {

    @Autowired
    private AppProperties appProperties;

    @Test
    public void test() {
        System.out.println(appProperties.getName());
    }
}

四、List 集合

app.user[0].name = zhangsan
app.user[0].age = 20
app.user[1].name = lisi
app.user[1].age = 21

app.addresses[0] = 127.0.0.1:8888
app.addresses[1] = 127.0.0.1:9999
# list 集合
app:
  user:
    - age: 20
      name: zhangsan
    - age: 21
      name: lisi
      
  addresses:
    - 127.0.0.1:8888
    - 127.0.0.1:9999

1. 使用 @ConfigurationProperties 注解

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.util.List;

@Data
@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {
    
    // 获取对象集合
    private List<User> userList;
    
    // 获取参数集合
    private List<String> addresses;

    @Data
    public static class User {

        private String name;
        private String age;
    }
}

2. 测试类

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;

@SpringBootTest(classes = Application.class)
@RunWith(SpringRunner.class)
public class ApplicationTest {

    @Autowired
    private AppProperties appProperties;

    @Test
    public void test() {
        
        // 对象集合
        List<AppProperties.User> userList = appProperties.getUserList();
        for (AppProperties.User user : userList) {
            System.out.println(user.getName());
            System.out.println(user.getAge());
        } 
        
        // 参数集合
        List<String> addresses = appProperties.getAddresses();
        for (String address : addresses) {
            System.out.println(address);
        }
    }
}

五、Map 集合

app.user.name = cnbai
app.user.address = xian
app:
  user: { name: cnbai , address: xian }

app:
  user:
    name: cnbai
    address: xian

1. 使用 @ConfigurationProperties 注解

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.util.Map;

@Data
@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {
    
    private Map<String , String> user;
}

2. 测试类

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Map;

@SpringBootTest(classes = Application.class)
@RunWith(SpringRunner.class)
public class ApplicationTest {

    @Autowired
    private AppProperties appProperties;

    @Test
    public void test() {
        
        Map<String , String> user = appProperties.getUser();
        for (Map.Entry<String, String> entry : user.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}

Properties 配置文件

@PropertySource + @ConfigurationProperties

1. user.properties

app.name = cnbai
app.address = xian

2. 使用 @ConfigurationProperties 注解

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;


/**
 * - @PropertySource 中 ignoreResourceNotFound 属性值为 true 时没找到指定配置文件的时候不报错
 */
@Data
@Component
@ConfigurationProperties(prefix = "app")
@PropertySource(value = "classpath:user.properties", encoding = "UTF-8", ignoreResourceNotFound = false) 
public class AppProperties {

    private String name;    
    private String address;
}

Yml 配置文件

@PropertySource + @ConfigurationProperties
yml 格式不支持 @PropertySource 注解直接导入配置,实现 PropertySourceFactory 接口,重写 createPropertySource 方法

1. test.yml

app:
  name: cnbai
  address: xian

2. Yml 文件处理类

import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.lang.Nullable;
 
import java.io.IOException;
import java.util.List;
import java.util.Optional;
 
public class YamlPropertySourceFactory implements PropertySourceFactory {
 
    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        String resourceName = Optional.ofNullable(name).orElse(resource.getResource().getFilename());
        assert resourceName != null;
        if (resourceName.endsWith(".yml") || resourceName.endsWith(".yaml")) {
            List<org.springframework.core.env.PropertySource<?>> yamlSources = new YamlPropertySourceLoader().load(resourceName, resource.getResource());
            return yamlSources.get(0);
        } else {
            return new DefaultPropertySourceFactory().createPropertySource(name, resource);
        }
    }
} 

3. 使用 @ConfigurationProperties 注解

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;


/**
 * - @PropertySource 中 factory 属性配置 Yml 文件处理类
 */
@Data
@Component
@ConfigurationProperties(prefix = "app")
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:test.yml", encoding = "UTF-8", ignoreResourceNotFound = false) 
public class AppProperties {

    private String name;    
    private String address;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值