SpringBoot 如何从配置文件读取值到对象中

目录
  • 一、实现方式
    • @ConfigurationProperties 注解
    • @Valid注解
  • 二、两者区别
  • 三、代码演示
  • 四、@PropertySource 读取指定配置文件
  • 五、@ImportResource:导入Spring配置文件
  • 六、思维导图

一、实现方式

@ConfigurationProperties 注解

(最好加上前缀prefix=“person”,标明是和配置文件中哪个开头的属性匹配)

推荐使用用在类上,从配置文件读取属性值,放到对象里面,复杂的结构也适用例如map,list,对象。支持校验:@Validated

@Valid注解

用在属性上,需要每个属性逐个绑定通过@value注解获取配置文件的值,不适合做复杂类型(map,list ,对象)值得获取不支持@Validated

二、两者区别

三、代码演示

使用@ConfigurationProperties注解

package com.wx.springboot20190911.demo.model;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Email;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * 1.ConfigurationProperties注解 从配置文件读取属性值,放到对象里面
 * 2.通过@value注解获取配置文件的值
 */
@Component//perosn 需要纳入spring ioc 容器里
@ConfigurationProperties(prefix = "person")//使用前缀标明具体的属性
@Validated
public class Person {
    @Email
    String email;
    String hello;
    String name;
    int age;
    boolean boss;
    Date birth;
    Map<String,String> maps;
    List<String> list;
    Dog dog;
    @Override
    public String toString() {
        return "Person{" +
                "email='" + email + '\'' +
                ", hello='" + hello + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", boss=" + boss +
                ", birth=" + birth +
                ", maps=" + maps +
                ", list=" + list +
                ", dog=" + dog +
                '}';
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getHello() {
        return hello;
    }
    public void setHello(String hello) {
        this.hello = hello;
    }
    public Dog getDog() {
        return dog;
    }
    public void setDog(Dog dog) {
        this.dog = dog;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public boolean isBoss() {
        return boss;
    }
    public void setBoss(boolean boss) {
        this.boss = boss;
    }
    public Date getBirth() {
        return birth;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
    }
    public Map<String, String> getMaps() {
        return maps;
    }
    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }
    public List<String> getList() {
        return list;
    }
    public void setList(List<String> list) {
        this.list = list;
    }
}
package com.wx.springboot20190911.demo.model;
public class Dog {
    String name;
    String color;
    int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", color='" + color + '\'' +
                ", age=" + age +
                '}';
    }
}

使用@Value注解

package com.wx.springboot20190911.demo.model;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.Email;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * 1.ConfigurationProperties注解 从配置文件读取属性值,放到对象里面,推荐使用,复杂的结构也适用例如map,list对象,
 * 支持 校验@Validated
 * 2.通过@value注解获取配置文件的值,不适合做复杂类型值得获取,不支持@Validated,支持
 */
@Component//perosn 需要纳入spring ioc 容器里
//@ConfigurationProperties(prefix = "person")
@Validated
public class Person1 {
    @Email
    @Value("${person1.email}")
    String email;
    @Value("${person1.hello}")
    String hello;
    @Value("${person1.name}")
    String name;
    @Value("#{12*3}")//支持计算
    int age;
    @Value("${person1.boss}")
    boolean boss;
    @Value("${person1.birth}")
    Date birth;
    Map<String,String> maps;
    List<String> list;
    Dog dog;
    public String getHello() {
        return hello;
    }
    public void setHello(String hello) {
        this.hello = hello;
    }
    public Dog getDog() {
        return dog;
    }
    public void setDog(Dog dog) {
        this.dog = dog;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public boolean isBoss() {
        return boss;
    }
    public void setBoss(boolean boss) {
        this.boss = boss;
    }
    public Date getBirth() {
        return birth;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
    }
    public Map<String, String> getMaps() {
        return maps;
    }
    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }
    public List<String> getList() {
        return list;
    }
    public void setList(List<String> list) {
        this.list = list;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    @Override
    public String toString() {
        return "Person1{" +
                "email='" + email + '\'' +
                ", hello='" + hello + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", boss=" + boss +
                ", birth=" + birth +
                ", maps=" + maps +
                ", list=" + list +
                ", dog=" + dog +
                '}';
    }
}

配置类(application.properties)代码

person.hello=luck
person.name=吴
#乱码的话 就setting设置下file encoding
person.list=ww,xx,rr
person.maps.k1=v1
person.maps.k2=v2
person.dog.name=cat
person.dog.color=red
person.dog.age=1
person.age=12
person.birth=2019/01/11
person.boss=false
person.email=www@qq.com
person1.hello=luck
person1.name=吴
#乱码的话 就setting设置下file encoding
person1.list=ww,xx,rr
person1.age=12
person1.birth=2019/01/11
person1.boss=false
person1.email=www

配置类(application.yml)代码:这种方式更加结构化

person:
  name: 霞
  age: 16
  boss : false
  birth: 2012/09/12
  maps: {k1: v1,k2: v2}
  list: [dog,cat ,house,rabbits]
  dog:
    name: ${person.hello}
    age: ${random.int(10)}
    color: white
  hello: yula

打印结果:使用第一种方式时,如果email不是"www@qq.com"这种格式,是不能运行成功的,但是使用@Value 不会校验,如下面是"www",一样能运行成功

Person{email='www@qq.com', hello='luck', name='吴', age=12, boss=false, birth=Fri Jan 11 00:00:00 CST 2019, maps={k1=v1, k2=v2}, list=[ww, xx, rr], dog=Dog{name='cat', color='red', age=1}}

Person1{email='www', hello='luck', name='吴', age=36, boss=false, birth=Fri Jan 11 00:00:00 CST 2019, maps=null, list=null, dog=null}

四、@PropertySource 读取指定配置文件

package com.wx.springboot20190911.demo.model;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Email;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * 1.ConfigurationProperties注解 从配置文件读取属性值,放到对象里面
 * 2.通过@value注解获取配置文件的值
 */
@PropertySource(value={"classpath:person.properties"})//指定读取person.properties配置文件
@Component//perosn 需要纳入spring ioc 容器里
@ConfigurationProperties(prefix = "person")//使用前缀标明具体的属性
@Validated
public class Person2 {
    @Email
    String email;
    String hello;
    String name;
    int age;
    boolean boss;
    Date birth;
    Map<String,String> maps;
    List<String> list;
    Dog dog;
    @Override
    public String toString() {
        return "Person{" +
                "email='" + email + '\'' +
                ", hello='" + hello + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", boss=" + boss +
                ", birth=" + birth +
                ", maps=" + maps +
                ", list=" + list +
                ", dog=" + dog +
                '}';
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getHello() {
        return hello;
    }
    public void setHello(String hello) {
        this.hello = hello;
    }
    public Dog getDog() {
        return dog;
    }
    public void setDog(Dog dog) {
        this.dog = dog;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public boolean isBoss() {
        return boss;
    }
    public void setBoss(boolean boss) {
        this.boss = boss;
    }
    public Date getBirth() {
        return birth;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
    }
    public Map<String, String> getMaps() {
        return maps;
    }
    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }
    public List<String> getList() {
        return list;
    }
    public void setList(List<String> list) {
        this.list = list;
    }
}

这里虽然指定了读取person.properties配置文件,但是由于prefix=“person”,导致还是读取了application.properties配置文件,因为application.properties权限最高,要想读取person.properties配置文件,就得改前缀名,例如改成prefix=“person2” person.properties配置文件的内容如下:

没改前缀名的结果演示:

Person{email='www@qq.com', hello='luck', name='吴', age=12, boss=false, birth=Fri Jan 11 00:00:00 CST 2019, maps={k1=v1, k2=v2}, list=[ww, xx, rr], dog=Dog{name='cat', color='red', age=1}}

Person1{email='www', hello='luck', name='吴', age=36, boss=false, birth=Fri Jan 11 00:00:00 CST 2019, maps=null, list=null, dog=null}

Person{email='www@qq.com', hello='luck', name='吴', age=12, boss=false, birth=Fri Jan 11 00:00:00 CST 2019, maps={k1=v1, k2=v2}, list=[ww, xx, rr], dog=Dog{name='cat', color='red', age=1}}

改前缀名的代码演示:

改了前缀名的结果演示:这时候读取的就是指定的配置文件的值

Person{email='www@qq.com', hello='luck', name='吴', age=12, boss=false, birth=Fri Jan 11 00:00:00 CST 2019, maps={k1=v1, k2=v2}, list=[ww, xx, rr], dog=Dog{name='cat', color='red', age=1}}

Person1{email='www', hello='luck', name='吴', age=36, boss=false, birth=Fri Jan 11 00:00:00 CST 2019, maps=null, list=null, dog=null}

Person{email='12345@qq.com', hello='springboot', name='指定读取配置文件', age=12, boss=false, birth=Wed Sep 11 00:00:00 CST 2019, maps={k2=v2, k1=v1}, list=[@Value, @PropertySource], dog=Dog{name='cat', color='red', age=1}}

注:只能读取 .properties 文件,无法读取 .yml 文件

五、@ImportResource:导入Spring配置文件

让配置文件里面的内容生效

Springboot 里没有Spring 的配置文件,我们自己编写的配置文件,也不能自动识别;

想让Spring的配置文件生效,加载进来,需使用该注解

写一个Person3 类,如图所示:

自定义一个Spring配置文件,如图所示:

在启动类上注解

测试:自定义的这个配置文件是否生效

演示结果:生效了

2019-09-11 22:15:12.247 INFO 7824 --- [ main] c.w.s.demo.DemoApplicationTests : Started DemoApplicationTests in 8.558 seconds (JVM running for 10.882)

Person{email='null', hello='null', name='null', age=0, boss=false, birth=null, maps=null, list=null, dog=null}

六、思维导图

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 详解SpringBoot读取配置文件的N种方法

    我们在项目开发中经常会用到配置信息,例如数据库连接的帐号.密码等,而为了方便维护,我们通常将这些信息放到配置文件中.在需要用到这些配置信息时,可以通过代码获取.下面我们看看Spring中有哪些获取配置信息的方法. PropertiesLoaderUtils读取 通过ClassPathResource加载配置文件资源,结合PropertiesLoaderUtils类读取,源码如下: ClassPathResource resource = new ClassPathResource("applic

  • springboot如何读取配置文件(application.yml)中的属性值

    在spring boot中,简单几步,读取配置文件(application.yml)中各种不同类型的属性值: 1.引入依赖: <!-- 支持 @ConfigurationProperties 注解 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId>

  • springboot读取配置文件中的参数具体步骤

    springBoot是java开发中会经常用到的框架,那么在实际项目中项目配置了springBoot框架,应该如何在项目中读取配置文件中的参数呢? 1.打开eclipse开发工具软件. 2.在项目中确保pom.xml文件已引用了[spring-boot-starter-web]jar包. 因为springBoot启动的时候会自动去获取项目中在resources文件录目下的名为application.properties参数配置文件. 3.在项目中的src/main/resource文件录目下创建

  • SpringBoot 如何从配置文件读取值到对象中

    目录 一.实现方式 @ConfigurationProperties 注解 @Valid注解 二.两者区别 三.代码演示 四.@PropertySource 读取指定配置文件 五.@ImportResource:导入Spring配置文件 六.思维导图 一.实现方式 @ConfigurationProperties 注解 (最好加上前缀prefix="person",标明是和配置文件中哪个开头的属性匹配) 推荐使用用在类上,从配置文件读取属性值,放到对象里面,复杂的结构也适用例如map,

  • java 如何给对象中的包装类设置默认值

    目录 给对象中的包装类设置默认值 处理方法如下 java属性的默认值 给对象中的包装类设置默认值 处理方法如下 主要适用于,对象中使用了包装类,但是不能给null需要有默认值的情况 /** * 处理对象中包装类,因为快捷签没有用包装类 * * @param object 对象 */ public static void handleParamDefault(Object object) { Class<?> aClass = object.getClass(); Field[] declare

  • SpringBoot yml配置文件读取方法详解

    目录 yaml介绍 yaml语法规则 yaml数据读取 Environment读取yaml全部属性数据 自定义对象封装指定数据 yaml介绍 YAML(YAML Ain't Markup Language),一种数据序列化格式 优点: 容易阅读 容易与脚本语言交互 以数据为核心,重数据轻格式 YANL文件扩展名 .yml(主流) .yaml 几种数据格式比较 yaml语法规则 大小写敏感 属性层级关系使用多行描述,每行结尾使用冒号结束 使用缩进表示层级关系,同层级左侧对齐,只允许使用空格(不允许

  • springboot配置文件读取pom文件信息方式

    目录 配置文件读取pom文件信息 解决的问题 解决 修改后的写法 maven打包命令 可能会出现的一些问题 Pom文件依赖配置说明 scope依赖范围 配置文件读取pom文件信息 解决的问题 springboot(当然别的也可以)多环境切换需要修改配置文件硬编码,打包时不够方便. 解决 配置文件能读取pom文件中的配置,根据命令选择不同配置注入springboot的配置文件中 pom配置文件: <!-- 环境 --> <profiles> <!-- 开发 --> <

  • SpringBoot 使用 @Value 注解读取配置文件给静态变量赋值

    1.application.properties 配置文件 mail.username=xue@163.com mail.password=xue mail.host=smtp.163.com mail.smtp.auth=true 2.给普通变量赋值,直接在变量上添加 @Value 注解 import org.springframework.beans.factory.annotation.Value; public class MailConfig { @Value("${mail.user

  • springboot 运行 jar 包读取外部配置文件的问题

    案例:本文主要描述linux系统执行jar包读取jar包同级目录的外部配置文件 方法一:相对路径设置配置文件 (1)在jar包同级目录创建配置文件conf.properties并写入配置数据: confData=data (2)开始写入自动化测试代码 //from www.fhadmin.cn public class Test{ public String getData() throws IOException { //读取配置文件 Properties properties = new P

  • springboot如何使用@Value获取配置文件的值

    使用@Value获取配置文件的值 1.创建配置文件(application.properties) spring.activemq.broker-url=tcp://localhost:61616 spring.activemq.user=admin spring.activemq.password=admin spring.activemq.in-memory=true spring.activemq.pool.enabled=false 2.创建测试类(MyController.java)

  • SpringBoot在yml配置文件中配置druid的操作

    最新版的druid和旧版在filter配置方面有些不同,以下是旧版druid中配置filter: spring: ##数据库连接信息 datasource: url: jdbc:mysql://localhost:3306/young username: root password: root driver-class-name: com.mysql.jdbc.Driver ###################以下为druid增加的配置########################### t

  • SpringBoot加载配置文件的实现方式总结

    目录 一.简介 二.代码实践 2.1.通过@value注解实现参数加载 2.2.通过@ConfigurationProperties注解实现参数加载 2.3.通过@PropertySource注解实现配置文件加载 2.4.通过自定义环境处理类,实现配置文件的加载 2.5.最后,我们来介绍一下yml文件读取 三.小结 一.简介 在实际的项目开发过程中,我们经常需要将某些变量从代码里面抽离出来,放在配置文件里面,以便更加统一.灵活的管理服务配置信息.比如,数据库.eureka.zookeeper.r

随机推荐