springboot读取配置文件的4种方式

配置文件让项目开发、管理、后期维护变得更加的优雅便捷,所以我们有必要学习下常见的springboot读取配置文件的方式。首先新建一个springboot项目,在application.properties配置文件中添加如下属性。

com.boot.demo1=spring
com.boot.demo2=boot
com.boot.demo3=学习

读取方式:
方式一:@Value("${xxx}")方式读取 ***.properties中的属性。

package com.yf.bootdemo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Value("${com.boot.demo1}")
    private String demo1;

    @Value("${com.boot.demo2}")
    private String demo2;

    @Value("${com.boot.demo3}")
    private String demo3;

    @RequestMapping("queryUser")
    public void queryUser() {
		System.out.println("demo1="+demo1+",demo2="+demo2+",demo3="+demo3);
    }
}

输出结果:
demo1=spring,demo2=boot,demo3=学习

方式二:使用Enviroment对象读取 ***.properties中的属性。

package com.yf.bootdemo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private Environment env;

    @RequestMapping("queryUser")
    public void queryUser() {
		System.out.println("demo1="+env.getProperty("com.boot.demo1")+",demo2="+env.getProperty("com.boot.demo2")+",demo3="+env.getProperty("com.boot.demo3"));
    }
}

输出结果:
demo1=spring,demo2=boot,demo3=学习

方式三:使用@ConfigurationProperties(prefix=“xxx”)读取

package com.yf.bootdemo.controller;

import com.yf.bootdemo.config.BootConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Autowired
    private BootConfig bootConfig;

    @RequestMapping("queryUser")
    public Object queryUser() {
 	     System.out.println(bootConfig.getDemo1()+","+bootConfig.getDemo2()+","+bootConfig.getDemo3()+","+bootConfig.getDemo4());
    }
}
输出结果:
demo1=spring,demo2=boot,demo4=null

1、demo4为null,这是因为上面三种方式默认都是读取*application.properties*配置文件,该配置文件中并没有com.boot.demo4属性,所以读取不到。
2、我们将com.boot.demo4属性放置在classpath:config/config.properties中了,需要指定配置文件路径,即下面注释的注解:@PropertySource(value={"classpath:config/config.properties"})即可读到。
3、如果我们所需要的配置属性存在于多个配置文件中可使用如下字符串数组形式配置,"classpath:"可省略。


***BootConfig.java类***
package com.yf.bootdemo.config;

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

@Component
@ConfigurationProperties(prefix = "com.boot")
//@ConfigurationProperties(prefix = "com.boots")
//@PropertySource(value={"classpath:config/config.properties"})
//@PropertySource(value={"classpath:config/config.properties",
//                                          "config/config2.properties"})
//@PropertySources(value={@PropertySource("classpath:config/config.properties"),
//                        @PropertySource("classpath:config2/config.properties")})
public class BootConfig {

//    @Value("${com.boots.demo1}")
    private String demo1;

    private String demo2;

    private String demo3;

    private String demo4;
    。。。。。。
省略getter/setter方法
   。。。。。。

方式四:读取map格式和list格式
方式一、方式二、方式三读取的都是***.properties配置文件中某个属性的value,那么如果将属性的key和value一起读取出来呢(Map)?如何读一次取多个同类的属性呢(List)?
在application.properties中添加如下配置属性:

#将如下属性读取成map格式
com.test.db.mysql[url]=http://www.baidu.com
com.test.db.mysql[username]=root
com.test.db.mysql[password]=123

#将如下属性读取成List格式
com.test.boot.engin[0]=http://www.google.com
com.test.boot.engin[1]=http://www.bing.com
com.test.boot.engin[2]=http://www.baidu.com
com.test.boot.engin[3]=http://www.sogou.com

Config如下:

package com.yf.bootdemo.config;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
//@ConfigurationProperties(prefix = "com.test.db")
@ConfigurationProperties(prefix = "com.test.boot")
public class CollectionConfig {

    Map<String, Object> mysql= new HashMap<>();

    public Map<String, Object> getMysql() {
        return mysql;
    }

    public void setMysql(Map<String, Object> mysql) {
        this.mysql = mysql;
    }

    List<String> enGiN = new ArrayList<>();

    public List<String> getEnGiN() {
        return enGiN;
    }

    public void setEnGiN(List<String> enGiN) {
        this.enGiN = enGiN;
    }
}


分别测试获取application.properties中的属性:

package com.yf.bootdemo.controller;

import com.yf.bootdemo.config.CollectionConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
public class UserController {

    @Autowired
    private CollectionConfig collectionConfig;
    
    @RequestMapping("queryUser")
    public void queryUser() {
       
        Map<String, Object> paramMap = collectionConfig.getMysql();
        System.out.println(CollectionUtils.isEmpty(paramMap));
        System.out.println("paramMap=" + paramMap);

        List<String> list = collectionConfig.getEnGiN();
        System.out.println(CollectionUtils.isEmpty(list));
        System.out.println(list.toString());
    }
}


两次输出结果:
第一次,获取map属性
false
paramMap={password=123, url=http://www.baidu.com, username=root}

第二次获取list属性
false
[http://www.google.com, http://www.bing.com, http://www.baidu.com, http://www.sogou.com]

注意点:
1.component中用于接受配置文件属性的集合(map或者list)名称要和properties中定义的key的最后一段保持一致(不区分大小写),即new的HashMap名称必须为mysql,List集合必须叫engin,不区分大小写。
2.@ConfigurationProperties中的prefix属性指定的key前缀必为集合名称前的全部路径,即这里的com.test.boot和com.test.db,少一级就会加载不到属性。

如不满足上面两个,就会出现集合属性为空的情况。

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 提供了多种读取配置文件方式,以下是其中几种常用的方式: 1. application.properties/application.yml:在 src/main/resources 目录下创建 application.properties 或 application.yml 文件,可以在其中设置应用程序的配置信息,例如: ``` server.port=8080 spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=root spring.datasource.password=123456 ``` 2. @Value 注解:在代码中使用 @Value 注解读取配置信息,例如: ``` @Value("${server.port}") private int serverPort; @Value("${spring.datasource.url}") private String dataSourceUrl; @Value("${spring.datasource.username}") private String dataSourceUsername; @Value("${spring.datasource.password}") private String dataSourcePassword; ``` 3. @ConfigurationProperties 注解:通过 @ConfigurationProperties 注解将配置文件中的属性值注入到 Bean 中,例如: ``` @ConfigurationProperties(prefix = "spring.datasource") public class DataSourceProperties { private String url; private String username; private String password; // getter/setter } ``` 4. Environment 接口:通过 Environment 接口读取配置信息,例如: ``` @Autowired private Environment env; int serverPort = env.getProperty("server.port", Integer.class); String dataSourceUrl = env.getProperty("spring.datasource.url"); String dataSourceUsername = env.getProperty("spring.datasource.username"); String dataSourcePassword = env.getProperty("spring.datasource.password"); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值