spring boot: 从配置文件中读取数据的常用方法(spring boot 2.3.4)

一,从配置文件中读取数据有哪些方法?

通常有3种用法:

1,直接使用value注解引用得到配置项的值

2,  封装到Component类中再调用

3,  用Environment类从代码中直接访问

生产环境中推荐使用第二种,用一个统一的文件来加载,

而不必写死到代码中,如果配置有变更时可以统一修改也更方便

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,演示项目的相关信息

1,项目地址:

https://github.com/liuhongdi/configvalue

2,功能说明:

        演示了从配置文件读取数据的方法

3,项目结构:如图:

三,配置文件说明

1,pom.xml

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

2,application.properties

#error
server.error.include-stacktrace=always
#errorlog
logging.level.org.springframework.web=trace
#profile
spring.profiles.active=prd

3,application-dev.properties

#images
app.goods.imagesUrlHost = http://127.0.0.1:81/goods
app.goods.imagesOrigDir = /data/file/html/goods/images
app.goods.imagesTmbDir = /data/file/html/goods/tmb

4,application-prd.properties

#images
app.goods.imagesUrlHost = http://file.lhdtest.com/goods
app.goods.imagesOrigDir = /data/estore/file/html/goods/images
app.goods.imagesTmbDir = /data/estore/file/html/goods/tmb

四,java代码说明:

1,ConfigValue.java

/*
* 从配置文件中读取的变量
*  lhd
*  2020.10.15
* */
@Component
public class ConfigValue {
    //imagesUrlHost
    @Value("${app.goods.imagesUrlHost}")
    public String imagesUrlHost;

    //imagesOrigDir
    @Value("${app.goods.imagesOrigDir}")
    public String imagesOrigDir;

    //imagesTmbDir
    @Value("${app.goods.imagesTmbDir}")
    public String imagesTmbDir;

}

用途:统一加载配置文件中的配置项

2,HomeController.java

@Controller
@RequestMapping("/home")
public class HomeController {

    @Resource
    private ConfigValue configValue;

    @Resource
    private Environment environment;

    //从配置文件读取变量imagesUrlHost
    @Value("${app.goods.imagesUrlHost}")
    private String imagesUrlHost;

    //三种方式打印从配置文件中读取到的变量值
    @GetMapping("/home")
    @ResponseBody
    public String home() {

        String res = "第一种方法:直接用value引用:"+imagesUrlHost+":<br/>";
        res += "第二种方法:封装到Component类中:"+configValue.imagesUrlHost+":<br/>";
        res += "第三种方法:environment:"+environment.getProperty("app.goods.imagesUrlHost")+":<br/>";

        return res;
    }
}

三种方法都可以使用,但Component类耦合度更低,使用时也更方便

五,测试效果

1,访问:

http://127.0.0.1:8080/home/home

返回:

第一种方法:直接用value引用:http://file.lhdtest.com/goods:
第二种方法:封装到Component类中:http://file.lhdtest.com/goods:
第三种方法:environment:http://file.lhdtest.com/goods:

2,切换profile为dev,可以看到访问的返回数据发生了变化

六,查看spring boot的版本:

  .   ____          _            __ _ _
 /\ / ___'_ __ _ _(_)_ __  __ _    
( ( )\___ | '_ | '_| | '_ / _` |    
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.4.RELEASE)
原文地址:https://www.cnblogs.com/architectforest/p/13822129.html