Spring Boot中读取配置属性的几种方式

简介: 前言  本文介绍Spring Boot中读取配置属性的几种方式,项目示例中用到的application.yml和application.properties定义如下:application.ymlapplication.properties@Value  @Value是比较常见的注入方式,功能强大但一般可读性较差。

前言

  本文介绍Spring Boot中读取配置属性的几种方式,项目示例中用到的application.ymlapplication.properties定义如下:

img_1527e31cf526e03c0b056bbacbba88c6.png
application.yml
img_ffbd9c750290f3280fc23811e54f9e44.png
application.properties

@Value

  @Value是比较常见的注入方式,功能强大但一般可读性较差。

    @Value("str")
    private String str; // 注入普通字符串
  
    @Value("${hello}")
    private String hello; // 注入配置属性

    @Value("#{systemProperties['os.name']}")
    private String systemPropertiesName; // 注入操作系统属性

    @Value("#{ T(java.lang.Math).random() * 100.0 }")
    private double randomNumber; //注入表达式结果

    @Value("#{userBean.name}")
    private String name; // 注入Bean属性

  下面通过@Value注解获取定义在配置文件的属性值:

  @SpringBootApplication
  public class AttributeApplication {

    private static final String SPRING_BOOT_HELLO = "spring-boot.hello";

    @Value("${" + SPRING_BOOT_HELLO + "}")
    private String hello;

    /**
     * 1. 通过@Value注解获取值
     */
    public void getAttrByValueAnnotation() {
      System.out.println("1. 通过@Value注解获取值: " + hello);
    }

    public static void main(String[] args) {
      ConfigurableApplicationContext applicationContext = SpringApplication.run(AttributeApplication.class, args);
      AttributeApplication bean = applicationContext.getBean(AttributeApplication.class);
      bean.getAttrByValueAnnotation();
    }
    
  }

  扩展说明:

   @SpringBootApplication
   public class AttributeApplication {
   
     private static final String SPRING_BOOT_STR_ARRAY = "spring-boot.str-array";
     private static final String SPRING_BOOT_INT_ARRAY = "spring-boot.int-array";

     /**
     * Attention : it is error if use Integer[]
     */
    @Value("${" + SPRING_BOOT_INT_ARRAY + "}")
    private int[] array;

    /**
     * 通过@Value注解获取数组
     */
    public void getArrayAttr() {
      System.out.println("5. 通过@Value注解获取数组: " + Arrays.toString(array));
    }

    @Value("#{'${" + SPRING_BOOT_STR_ARRAY + "}'.split(',')}")
    private List<String> list;

    /**
     * 通过@Value注解获取List
     */
    public void getListAttr() {
      System.out.println("6. 通过@Value注解获取List: " + list.toString());
    }
    
    public static void main(String[] args) {
      ConfigurableApplicationContext applicationContext = SpringApplication.run(AttributeApplication.class, args);
      AttributeApplication bean = applicationContext.getBean(AttributeApplication.class);
      bean.getArrayAttr();
          bean.getListAttr();
    }
    
  }

Environment

  通过注入获取Environment对象,然后再获取定义在配置文件的属性值:

  @SpringBootApplication
  public class AttributeApplication {

    private static final String SPRING_BOOT_HELLO = "spring-boot.hello";

    @Resource
    private Environment environment;

     /**
     * 2. 通过注入Environment获取值
     */
    public void getAttrByEnvironment() {
      String property = environment.getProperty(SPRING_BOOT_HELLO);
      System.out.println("2-1. 通过注入Environment获取值: " + property);
    }
    
    public static void main(String[] args) {
      ConfigurableApplicationContext applicationContext = SpringApplication.run(AttributeApplication.class, args);
      AttributeApplication bean = applicationContext.getBean(AttributeApplication.class);
      bean.getAttrByEnvironment();
    }

  }

  还可以在启动类中通过ApplicationContext获取Environment对象后再获取值:

  @SpringBootApplication
  public class AttributeApplication {
  
    private static final String UNDEFINED = "undefined";
    private static final String SPRING_BOOT_HELLO = "spring-boot.hello";
  
      public static void main(String[] args) {
      ConfigurableApplicationContext applicationContext = SpringApplication.run(AttributeApplication.class, args);
      System.out.println("2-2. 通过ApplicationContext获取Environment后再获取值: " + applicationContext
                      .getEnvironment().getProperty(SPRING_BOOT_HELLO, UNDEFINED));
    }
  
  }

@ConfigurationProperties

  @ConfigurationProperties作用在类上,用于注入Bean属性,然后再通过当前Bean获取注入值:

  @SpringBootApplication
  public class AttributeApplication {

    private static final String APPLICATION_YML = "application.yml";
    private static final String SPRING_BOOT_PREFIX = "spring-boot";

    @Data
    @Component
    @PropertySource("classpath:" + APPLICATION_YML)
    @ConfigurationProperties(prefix = SPRING_BOOT_PREFIX)
    class Attribute {

      private String hello;
      private String world;

    }

    @Resource
    private Attribute attribute;

    /**
     * 3. 通过@ConfigurationProperties注入对象属性获取
     */
    public void getAttrByConfigurationPropertiesAnnotation() {
      System.out.println("3. 通过@ConfigurationProperties注入对象属性获取: " + attribute);
    }
    
    public static void main(String[] args) {
      ConfigurableApplicationContext applicationContext = SpringApplication.run(AttributeApplication.class, args);
      AttributeApplication bean = applicationContext.getBean(AttributeApplication.class);
      bean.getAttrByConfigurationPropertiesAnnotation();
    }
    
  }

PropertiesLoaderUtils

  @SpringBootApplication
  public class AttributeApplication {
  
      private static final String UNDEFINED = "undefined";
      private static final String APPLICATION_PROPERTIES = "application.properties";
       private static final String SPRING_BOOT_HELLO = "spring-boot.hello";

    /**
     * 4. 通过PropertiesLoaderUtils获取(注意,此工具类仅可处理.properties或.xml配置文件)
     */
    public void getAttrByPropertiesLoaderUtils() {
      try {
        ClassPathResource resource = new ClassPathResource(APPLICATION_PROPERTIES);
        Properties properties = PropertiesLoaderUtils.loadProperties(resource);
        String property = properties.getProperty(SPRING_BOOT_HELLO, UNDEFINED);
        System.out.println("4. 通过PropertiesLoaderUtils获取: " + property);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    
    public static void main(String[] args) {
      ConfigurableApplicationContext applicationContext = SpringApplication.run(AttributeApplication.class, args);
      AttributeApplication bean = applicationContext.getBean(AttributeApplication.class);
      bean.getAttrByPropertiesLoaderUtils();
    }

  }

说明

  源码地址

目录
相关文章
|
3天前
|
运维 Java 测试技术
Spring运维之boo项目表现层测试加载测试的专用配置属性以及在JUnit中启动web服务器发送虚拟请求
Spring运维之boo项目表现层测试加载测试的专用配置属性以及在JUnit中启动web服务器发送虚拟请求
9 3
|
7天前
|
消息中间件 Java Kafka
集成Kafka到Spring Boot项目中的步骤和配置
集成Kafka到Spring Boot项目中的步骤和配置
36 7
|
3天前
|
运维 Java 关系型数据库
Spring运维之boot项目bean属性的绑定读取与校验
Spring运维之boot项目bean属性的绑定读取与校验
12 2
|
3天前
|
存储 运维 Java
Spring运维之boot项目开发关键之日志操作以及用文件记录日志
Spring运维之boot项目开发关键之日志操作以及用文件记录日志
17 2
|
3天前
|
Java Maven
springboot项目打jar包后,如何部署到服务器
springboot项目打jar包后,如何部署到服务器
13 1
|
3天前
|
XML 运维 Java
Spring运维之boot项目打包jar和插件运行并且设置启动时临时属性和自定义配置文件
Spring运维之boot项目打包jar和插件运行并且设置启动时临时属性和自定义配置文件
11 1
|
16小时前
|
XML Java 数据格式
|
16小时前
|
Java Spring
|
3天前
springboot2.4.5使用pagehelper分页插件
springboot2.4.5使用pagehelper分页插件
7 0
|
3天前
|
Java Spring
spring基于注解配置数据源
spring基于注解配置数据源
8 0