SpringBoot读取properties配置文件中的数据的三种方法

 更新时间:2024年06月21日 10:43:33   作者:程序员null  
本文主要介绍了SpringBoot读取properties配置文件中的数据的三种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

Spring Boot最常用的3种读取properties配置文件中数据的方法:

1、使用@Value注解读取

读取properties配置文件时,默认读取的是application.properties。

application.properties:

demo.name=Name
demo.age=18

Java代码:

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

@RestController
public class GatewayController {

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

    @Value("${demo.age}")
    private String age;

    @RequestMapping(value = "/gateway")
    public String gateway() {
        return "get properties value by ''@Value'' :" +
                //1、使用@Value注解读取
                " name=" + name +
                " , age=" + age;
    }
}

运行结果如下:

这里,如果要把

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

部分放到一个单独的类A中进行读取,然后在类B中调用,则要把类A增加@Component注解,并在类B中使用@Autowired自动装配类A,代码如下。

类A:

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

@Component
public class ConfigBeanValue {

    @Value("${demo.name}")
    public String name;

    @Value("${demo.age}")
    public String age;
}

类B:

import cn.wbnull.springbootdemo.config.ConfigBeanValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GatewayController {

    @Autowired
    private ConfigBeanValue configBeanValue;

    @RequestMapping(value = "/gateway")
    public String gateway() {
        return "get properties value by ''@Value'' :" +
                //1、使用@Value注解读取
                " name=" + configBeanValue.name +
                " , age=" + configBeanValue.age;
    }
}

运行结果如下:

​注意:如果@Value${}所包含的键名在application.properties配置文件中不存在的话,会抛出异常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configBeanValue': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'demo.name' in value "${demo.name}"

2、使用Environment读取

application.properties:

demo.sex=男
demo.address=山东

Java代码:

import cn.wbnull.springbootdemo.config.ConfigBeanValue;
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 GatewayController {

    @Autowired
    private ConfigBeanValue configBeanValue;

    @Autowired
    private Environment environment;

    @RequestMapping(value = "/gateway")
    public String gateway() {
        return "get properties value by ''@Value'' :" +
                //1、使用@Value注解读取
                " name=" + configBeanValue.name +
                " , age=" + configBeanValue.age +
                "<p>get properties value by ''Environment'' :" +
                //2、使用Environment读取
                " , sex=" + environment.getProperty("demo.sex") +
                " , address=" + environment.getProperty("demo.address");
    }
}

运行,发现中文乱码:

​这里,我们在application.properties做如下配置:

server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.messages.encoding=UTF-8

然后修改IntelliJ IDEA,File --> Settings --> Editor --> File Encodings ,将最下方Default encoding for properties files设置为UTF-8,并勾选Transparent native-to-ascii conversion。

​重新运行结果如下:

3、使用@ConfigurationProperties注解读取

在实际项目中,当项目需要注入的变量值很多时,上述所述的两种方法工作量会变得比较大,这时候我们通常使用基于类型安全的配置方式,将properties属性和一个Bean关联在一起,即使用注解@ConfigurationProperties读取配置文件数据。

在src\main\resources下新建config.properties配置文件:

demo.phone=10086
demo.wife=self

创建ConfigBeanProp并注入config.properties中的值:

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

@Component
@ConfigurationProperties(prefix = "demo")
@PropertySource(value = "config.properties")
public class ConfigBeanProp {

    private String phone;

    private String wife;

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getWife() {
        return wife;
    }

    public void setWife(String wife) {
        this.wife = wife;
    }
}

@Component 表示将该类标识为Bean

@ConfigurationProperties(prefix = "demo")用于绑定属性,其中prefix表示所绑定的属性的前缀。

@PropertySource(value = "config.properties")表示配置文件路径。

使用时,先使用@Autowired自动装载ConfigBeanProp,然后再进行取值,示例如下:

import cn.wbnull.springbootdemo.config.ConfigBeanProp;
import cn.wbnull.springbootdemo.config.ConfigBeanValue;
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 GatewayController {

    @Autowired
    private ConfigBeanValue configBeanValue;

    @Autowired
    private Environment environment;

    @Autowired
    private ConfigBeanProp configBeanProp;

    @RequestMapping(value = "/gateway")
    public String gateway() {
        return "get properties value by ''@Value'' :" +
                //1、使用@Value注解读取
                " name=" + configBeanValue.name +
                " , age=" + configBeanValue.age +
                "<p>get properties value by ''Environment'' :" +
                //2、使用Environment读取
                " sex=" + environment.getProperty("demo.sex") +
                " , address=" + environment.getProperty("demo.address") +
                "<p>get properties value by ''@ConfigurationProperties'' :" +
                //3、使用@ConfigurationProperties注解读取
                " phone=" + configBeanProp.getPhone() +
                " , wife=" + configBeanProp.getWife();
    }
}

运行结果如下:

到此这篇关于SpringBoot读取properties配置文件中的数据的三种方法的文章就介绍到这了,更多相关SpringBoot properties读取配置文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

相关文章

  • 详解Spring Cache使用Redisson分布式锁解决缓存击穿问题

    详解Spring Cache使用Redisson分布式锁解决缓存击穿问题

    本文主要介绍了详解Spring Cache使用Redisson分布式锁解决缓存击穿问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-04-04
  • Maven依赖冲突原因以及解决方法

    Maven依赖冲突原因以及解决方法

    依赖冲突是指项目依赖的某一个 jar 包,有多个不同的版本,因而造成类包版本冲突依赖冲突很经常是类包之间的间接依赖引起的,本文将给大家介绍Maven依赖冲突原因以及解决方法,需要的朋友可以参考下
    2023-12-12
  • 浅谈Java中方法参数传递的问题

    浅谈Java中方法参数传递的问题

    下面小编就为大家带来一篇浅谈Java中方法参数传递的问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-08-08
  • MyBatis-Plus的apply用法小结

    MyBatis-Plus的apply用法小结

    apply方法是一个非常有用的功能,apply方法允许用户直接在QueryWrapper或LambdaQueryWrapper中添加原生SQL片段,本文就详细的介绍一下apply方法,感兴趣的可以了解一下
    2024-10-10
  • Spring BeanFactory工厂使用教程

    Spring BeanFactory工厂使用教程

    Spring的本质是一个bean工厂(beanFactory)或者说bean容器,它按照我们的要求,生产我们需要的各种各样的bean,提供给我们使用。只是在生产bean的过程中,需要解决bean之间的依赖问题,才引入了依赖注入(DI)这种技术
    2023-02-02
  • springboot幂等切片的实现

    springboot幂等切片的实现

    本文主要介绍了springboot幂等切片的实现,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • 深度解析Java中的国际化底层类ResourceBundle

    深度解析Java中的国际化底层类ResourceBundle

    做项目应该都会实现国际化,那么大家知道Java底层是如何实现国际化的吗?这篇文章就来和大家深度解析一下Java中的国际化底层类ResourceBundle,希望对大家有所帮助
    2023-03-03
  • spring boot2.0图片上传至本地或服务器并配置虚拟路径的方法

    spring boot2.0图片上传至本地或服务器并配置虚拟路径的方法

    最近写了关于图片上传至本地文件夹或服务器,上传路径到数据库,并在上传时预览图片。本文通过实例代码给大家分享spring boot2.0图片上传至本地或服务器并配置虚拟路径的方法,需要的朋友参考下
    2018-12-12
  • Java 不使用第三方变量交换两个变量值的四种方法详解

    Java 不使用第三方变量交换两个变量值的四种方法详解

    这篇文章主要介绍了四种不使用第三方变量交换两个变量值的方法。文中对于四种方法进行了详细的分析,需要的小伙伴们可以跟随小编一起学习一下
    2021-12-12
  • Spring Boot利用@Async异步调用:使用Future及定义超时详解

    Spring Boot利用@Async异步调用:使用Future及定义超时详解

    这篇文章主要给大家介绍了关于Spring Boot利用@Async异步调用:使用Future及定义超时的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用spring boot具有一定的参考学习价值,需要的朋友可以参考下
    2018-05-05

最新评论