Springboot中yml文件读取

SpringBoot的.yml文件是一个非常简洁明了的配置文件,可看作.properties的精简版。一般来讲,我们通过@Value这个注解就可以直接获取到某个properties的值。如:有如下配置:

spring:
    datasource:
        druid:
            localhost:
                driverClassName: com.mysql.jdbc.Driver
                url: jdbc:mysql://localhost:3306/paas-dashboard?useUnicode=true&characterEncoding=utf8
                username: root
                password:123
             master:
                driverClassName: oracle.jdbc.OracleDriver
                url: jdbc:oracle:thin:@//172.21.0.73:1621/tthradb
                username: dbchnesbcfgcha
                password: dbchnesbcfgcha

一般来讲,直接通过@Value(spring.datasource.druid.localhost.driverClassName)直接获取到这个值了。

但是如果需要直接获取到localhost下面所有的配置呢?或者自己指定某一层下面所有的配置信息呢?

简单示例

SpringBoot中还有一种非常强大的注解@ConfigurationProperties,使用该注解可直接将yml的配置直接注入到某个对象中。

如:yml中有如下配置:

        info:
            user:
                name: zhangsan
                age: 14

这时,我们定义个User对象:

class User{
    String name;
    int age;

//getter 及 setter方法
   
}

在Spring容器中直接通过@ConfigurationProperties来注入,需要指定前缀到配置文件中user的上一层。对象名必须同yml中的配置。

@Component
@PropertySource("classpath:application-druid.yml") //指定yml文件位置
@ConfigurationProperties(prefix = "info")
public class YmlConfig{

    User user = new User();
//user getter及setter方法
}

Spring容器启动后,yml中的配置的属性即注入到user对象。

或者我们也可以用个Map来进行封装,配置文件中的属性无非就是key:value的形式,同样定义user对象:

@Component
@PropertySource("classpath:application-druid.yml") //指定yml文件位置
@ConfigurationProperties(prefix = "info")       
public class YmlConfig{

    Map<String,String> user = new HashMap<>();
//user getter及setter方法
}

同样也能注入到user的Map对象。

指定任意层

如本文开始的那个yml配置文件的配置,如果,我想直接获取到所有的数据源的配置,那么就必须要指定一个对象能装下所有的这些配置,可以自定义对象,或者直接使用Map。如,我们定义如下的Map:

@Component
@ConfigurationProperties(prefix = "spring.datasource")
public class YmlConfig{

    Map<String,Map<String,String>> druid = new HashMap<>();
//user getter及setter方法
}

Spring容器其中后,配置文件中spring.datasource.druid以下的配置属性同样能注入到druid对象中去。

同样指定其他层的配置,只要符合某个对象的数据结构,就能将配置的属性注入到该对象中去。

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值