SpringBoot配置文件的读取(包括list、map类型)

前言

添加配置文件处理器的依赖,这样在编写配置文件的时候就会有提示了。

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>

有了依赖,可以直接使用application.properties文件为我们工作了,这是Springboot的默认文件,它会通过其机制读取到上下文中,这样就可以引用它了

读取配置文件

在使用maven项目中,配置文件会放在resources根目录下。
我们的springBoot是用Maven搭建的,所以springBoot的默认配置文件和自定义的配置文件都放在此目录。
springBoot的 默认配置文件为 application.properties 或 application.yml,这里我们使用 application.properties

首先在application.properties中添加我们要读取的数据。

server.port = 8081

custom.name = lonewalker
custom.age = 18

第一种方式

我们可以通过@Value注解,这是Spring就有的,使用${...}占位符来读取配置在属性文件中的内容,既可以加在属性也可以加在方法上

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class User {

    @Value("${custom.name}")
    private String name;

    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    public Integer getAge() {
        return age;
    }

    @Value("${custom.age}")
    public void setAge(Integer age) {
        this.age = age;
    }
}

我们在测试环境试一下:

@SpringBootTest
class DemoApplicationTests {

    @Autowired
    User user;

    @Test
    void contextLoads() {
        System.out.println(user.getName());
        System.out.println(user.getAge());
    }

}

第二种方式:

如果有很多我们就要写很多@Value,就会很麻烦,于是就有第二种方式

通过注解@ConfigurationProperties(prefix="配置文件中的key的前缀")可以将配置文件中的配置自动与实体进行映射,默认从全局配置文件中获取值

@ConfigurationProperties("custom")这里的字符串custom会和类中的属性名称组成全限定名去配置文件中查找

@Component
@ConfigurationProperties(prefix = "custom")
public class User {

    private String name;

    private Integer age;

getter()... setter()...
}

扩展:

1、如何获取list数据

test.list=aaa,bbb,ccc

又该如何读取呢?

@SpringBootTest
class DemoApplicationTests {

    @Value("#{'${test.list:}'.empty ? null : '${test.list:}'.split(',')}")
    private List<String> testList;

    @Test
    void contextLoads() {
      if (testList == null){
          System.out.println("empty");
      }else{
          for (String list:testList
               ) {
              System.out.println(list);
          }
      }
    }

}

首先这是一个EL表达式,${test.list:} 是为它加上默认值但是这样有个问题,当不配置该 key 值,默认值会为空串,它的 length = 1,这样解析出来 list 的元素个数就不是空了

所以在此之前先判断一下是否为空,最终写成这样@Value("#{'${test.list:}'.empty ? null : '${test.list:}'.split(',')}") 就完美了,遍历的结果

2、如何获取map数据

test.map={name:"守约",force:"95"}

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
1. 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> ``` 2. 在application.properties中添加以下配置: ``` # 主库配置 spring.datasource.master.url=jdbc:mysql://localhost:3306/master?useUnicode=true&characterEncoding=utf-8&useSSL=false spring.datasource.master.username=root spring.datasource.master.password=root spring.datasource.master.driver-class-name=com.mysql.jdbc.Driver # 从库配置 spring.datasource.slave.url=jdbc:mysql://localhost:3306/slave?useUnicode=true&characterEncoding=utf-8&useSSL=false spring.datasource.slave.username=root spring.datasource.slave.password=root spring.datasource.slave.driver-class-name=com.mysql.jdbc.Driver # 配置多个从库,用逗号分隔 spring.datasource.slave2.url=jdbc:mysql://localhost:3306/slave2?useUnicode=true&characterEncoding=utf-8&useSSL=false spring.datasource.slave2.username=root spring.datasource.slave2.password=root spring.datasource.slave2.driver-class-name=com.mysql.jdbc.Driver # 配置读写分离 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.read-type=READ_ONLY spring.datasource.master.slaves=slave,slave2 ``` 3. 在代码中使用@Primary注解来指定默认的数据源: ``` @Configuration public class DataSourceConfig { @Bean(name = "masterDataSource") @ConfigurationProperties(prefix = "spring.datasource.master") public DataSource masterDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "slaveDataSource") @ConfigurationProperties(prefix = "spring.datasource.slave") public DataSource slaveDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "slave2DataSource") @ConfigurationProperties(prefix = "spring.datasource.slave2") public DataSource slave2DataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "dynamicDataSource") @Primary // 指定默认的数据源 public DataSource dynamicDataSource() { DynamicDataSource dynamicDataSource = new DynamicDataSource(); dynamicDataSource.setDefaultTargetDataSource(masterDataSource()); Map<Object, Object> dataSourceMap = new HashMap<>(); dataSourceMap.put("master", masterDataSource()); dataSourceMap.put("slave", slaveDataSource()); dataSourceMap.put("slave2", slave2DataSource()); dynamicDataSource.setTargetDataSources(dataSourceMap); return dynamicDataSource; } } ``` 4. 实现自定义的动态数据源: ``` public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceContextHolder.getDataSourceType(); } } ``` 5. 创建一个数据源上下文,用于保存当前线程使用的数据类型: ``` public class DataSourceContextHolder { private static final ThreadLocal<String> contextHolder = new ThreadLocal<>(); public static void setDataSourceType(String dataSourceType) { contextHolder.set(dataSourceType); } public static String getDataSourceType() { return contextHolder.get(); } public static void clearDataSourceType() { contextHolder.remove(); } } ``` 6. 在service层中根据需要调用不同的数据源: ``` @Service public class UserService { @Autowired private UserDao userDao; public List<User> findAll() { // 从主库读取数据 DataSourceContextHolder.setDataSourceType("master"); return userDao.findAll(); } public User findById(Long id) { // 从从库1读取数据 DataSourceContextHolder.setDataSourceType("slave"); return userDao.findById(id); } public void save(User user) { // 写入主库 DataSourceContextHolder.setDataSourceType("master"); userDao.save(user); } public void deleteById(Long id) { // 写入主库 DataSourceContextHolder.setDataSourceType("master"); userDao.deleteById(id); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LoneWalker、

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值