Spring系列之——springboot解析resources.application.properties文件

  摘要:本文通过讲解如何解析application.properties属性,介绍了几个注解的运用@Value @ConfigurationProperties @EnableConfigurationProperties @Autowired @ConditionalOnProperty

1 准备

1.1 搭建springboot

1.2 写一个controller类

package com.gbm.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by Administrator on 2019/2/20.
 */

@Controller
public class IndexController {
    @RequestMapping("/index")
    @ResponseBody
    public String index() {
        return "我爱北京天安门!";
    }
}

2 几种获取属性值方式

  配置application.properties

value.local.province=Zhejiang
value.local.city=Hangzhou

complex.other.province=Jiangsu
complex.other.city=Suzhou
complex.other.flag=false

2.1 使用注解@Value("${xxx}")获取指定属性值

  2.1.1 在controller类中获取属性值

package com.gbm.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by Administrator on 2019/2/20.
 */

@Controller
public class IndexController {
    @Value("${value.local.province}")
    private String province;

    @Value("${value.local.city}")
    private String city;

    @RequestMapping("/index")
    @ResponseBody
    public String index() {
        StringBuffer sb = new StringBuffer();
        sb.append(this.city);
        sb.append(",");
        sb.append(this.province);
        sb.append(" ");
        return sb.toString();
    }
}

  2.1.2 任何浏览器上运行 http://localhost:8080/index,结果如下  

  

2.2 使用注解@ConfigurationProperties(prefix = "xxx")获得前缀相同的一组属性,并转换成bean对象

  2.2.1 写一个实体类

package com.gbm.models;

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

/**
 * Created by Administrator on 2019/2/21.
 */
@Component
@ConfigurationProperties(prefix = "complex.other")
public class Complex {
    private String province;
    private String city;
    private Boolean flag;

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public Boolean getFlag() {
        return flag;
    }

    public void setFlag(Boolean flag) {
        this.flag = flag;
    }

    @Override
    public String toString() {
        return "Complex{" +
                "province=‘" + province + ‘\‘‘ +
                ", city=‘" + city + ‘\‘‘ +
                ", flag=" + flag +
                ‘}‘;
    }
}

  2.2.2 在controller类中获取属性值

package com.gbm.controller;

import com.gbm.models.Complex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by Administrator on 2019/2/20.
 */

@Controller
public class IndexController {
    @Autowired
    private Complex complex;

    @RequestMapping("/index")
    @ResponseBody
    public String index() {
        return complex.toString();
    }
}

  2.2.3 在SpringBootApplication中使Configuration生效

package com.gbm.myspingboot;

import com.gbm.models.Complex;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;

@SpringBootApplication
@ComponentScans({@ComponentScan("com.gbm.controller"), @ComponentScan("com.gbm.models")})
@EnableConfigurationProperties(Complex.class)
@ConditionalOnProperty(value = "complex.other.town", matchIfMissing = true)
public class MyspingbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyspingbootApplication.class, args);
    }
}

  2.2.4 任何浏览器上运行 http://localhost:8080/index,结果如下 

  

3 总结

  关于解析application.properties文件,最重要的是对注解的使用,本文主要涉及到如下几个注解的运用

  @Value("${xxx}")——获取指定属性值

  @ConfigurationProperties(prefix = "xxx")——获得前缀相同的一组属性,并转换成bean对象

  @EnableConfigurationProperties(xxx.class)——使Configuration生效,并从IOC容器中获取bean

  @Autowired——自动注入set和get方法

  @ConditionalOnProperty(value = "complex.other.town", matchIfMissing = true)——缺少该property时是否可以加载,如果是true,没有该property也会正常加载;如果是false则会抛出异常。例如

package com.gbm.myspingboot;

import com.gbm.models.Complex;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;

@SpringBootApplication
@ComponentScans({@ComponentScan("com.gbm.controller"), @ComponentScan("com.gbm.models")})
@EnableConfigurationProperties(Complex.class)
@ConditionalOnProperty(value = "complex.other.town", matchIfMissing = false)
public class MyspingbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyspingbootApplication.class, args);
    }
}

matchIfMissing=false代码

Error starting ApplicationContext. To display the conditions report re-run your application with ‘debug‘ enabled.
2019-02-21 23:30:56.532 ERROR 3152 --- [           main] o.s.boot.SpringApplication               : Application run failed

原文地址:https://www.cnblogs.com/guobm/p/10415795.html

时间: 2024-10-13 06:10:34

Spring系列之——springboot解析resources.application.properties文件的相关文章

springboot官网->application.properties文件

springboot application.properties 2.1.6.RELEASE 原文地址:https://www.cnblogs.com/gogogofh/p/11232502.html

SpringBoot读取application.properties文件

SpringBoot读取application.properties文件,通常有3种方式 1. @Value  例如: @Value("${spring.profiles.active}") private String profileActive;------相当于把properties文件中的spring.profiles.active注入到变量profileActive中 2. @ConfigurationProperties  例如: @Component@Configurat

微服务之springboot 自定义配置(一)Application.properties文件

配置的文件的格式 springboot可以识别两种格式的配置文件,分别是yml和properties 文件.我们可以将application.properties文件换成application.yml,这两个文件都可以被SpringBoot自动识别并加载,但是如果是自定义的配置文件,就最好还是使用properties格式的文件,因为SpringBoot中暂时还并未提供手动加载yml格式文件的功能(这里指注解方式). yml 配置文件 属性格式:配置的属性和属性值要有空格隔开.没有空格报:java

spring boot application.properties文件外部配置

spring boot application.properties文件外部配置 官方文档 原文地址:https://www.cnblogs.com/lwmp/p/9836791.html

spring mvc利用MultipartResolver解析Multipart/form-data进行文件上传

之前的表单数据都是文本数据,现记录:利用MultipartResolver进行文件上传. ①首先,需引入commons-fileUpload和commons-io jar包,pom.xml文件的坐标: <properties>      <spring.version>3.2.1.RELEASE</spring.version>  </properties>  <dependencies>          <dependency> 

application.properties 文件和 application.yml 文件有什么区别呢?

application.properties  文件和 application.yml 文件有什么区别呢? yml文件的好处,天然的树状结构,一目了然,实质上跟properties是差不多的. 官方给的很多demo,都是用yml文件配置的. 注意点: 1,原有的key,例如spring.jpa.properties.hibernate.dialect,按“.”分割,都变成树状的配置 2,key后面的冒号,后面一定要跟一个空格 3,把原有的application.properties删掉.然后一定

fmt 国际化格式标签库(读取application.properties文件)

国际化格式标签库包括国际化,消息和数字日期格式化: (1) 国际化:<fmt:setLocale> <fmt::requestEncoding> 如: <%@ page language="java" contentType="text/html; charset=gb2312" import="java.util.*"%> <%@ taglib prefix="c" uri=&quo

spring-boot默认的application.properties属性

# =================================================================== # COMMON SPRING BOOT PROPERTIES # # This sample file is provided as a guideline. Do NOT copy it in its # entirety to your own application. ^^^ # ===================================

关于tomcat下spring无法加载依赖jar中properties文件的原因分析

我们经常把spring需要加载的properties文件放在java/resources下面,这样存放的问题导致properties在打包后就在jar的根目录下,所以我们的spring的配置路径就是classpath*:xxx.properties,但是这样的jar我们在被其他项目引用的时候会发现properties文件老是无法加载,就这个问题从spring的源码来找找为什么会这样. 首先properties是当做一个resource来加载的,实现加载的是org.springframework.