Spring Boot学习笔记----读取配置文件


Springboot默认配置信息,都放置在application.properties文件中,位于工程目录的src/main/resource下。

springboot中通过获取配置文件配置值获取配置文件中的值 springboot获取配置文件中的变量_spring

本文记录两种方法
(1)如何获取默认配置信息
(2)如何获取自定义配置信息

常见问题
(1)Spring Boot Annotion processor not found in classpath
(2)Re-run Spring Boot Configuration Annotation Processor to update generated metadata

如何获取默认配置信息

配置信息可以通过@Value与属性变量进行绑定。

例如,在application.properties文件中定义如下变量

Test.fileName="1.txt"
path=C:/output
fileNum=1
  • 1
  • 2
  • 3

我们在Controller中,进行变量绑定,然后打印内容。核心代码如下

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


@RestController
public class ConfigController {

    Logger logger= LoggerFactory.getLogger(ConfigController.class);

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

    @Value("${path}")
    private String path;

    @Value("${fileNum}")
    private int num;

    @RequestMapping("/getConfig")
    public void getConfig(){
        ("fileName="+name);
        ("path="+path);
        ("fileNum="+num);
    }
}

执行结果如下

2017-12-06 11:06:34.461  INFO 9504 --- [nio-8080-exec-6] com.gemalto.configtest.ConfigController  : fileName="1.txt"
2017-12-06 11:06:34.461  INFO 9504 --- [nio-8080-exec-6] com.gemalto.configtest.ConfigController  : path=C:/output
2017-12-06 11:06:34.461  INFO 9504 --- [nio-8080-exec-6] com.gemalto.configtest.ConfigController  : fileNum=1

如果配置具有相同的prefix,那么可以使用@ConfigurationProperties(prefix=”my”)进行简化绑定。

例如,我们在application.properties中添加

=breakloop1
my.age=10
my.location=BJ1

读取时,我们创建配置类MyConfigController2。

@RestController
@ConfigurationProperties(prefix="my")
public class MyConfigController2 {

    Logger logger= LoggerFactory.getLogger(MyConfigController2.class);

    private String name;

    private int age;

    private String location;

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getLocation() {
        return location;
    }

    public void setName(String name) {
         = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    @RequestMapping("/getMyConfig2")
    public void getMyConfig(){
        ("my name is "+name+", "+ age +" years old, "+location);
    }

}

执行结果如下:

2017-12-06 12:12:03.387  INFO 8504 --- [nio-8080-exec-6] c.g.configtest.MyConfigController2       : my name is breakloop1, 10 years old, BJ1
  • 1

如果不想使用@Value进行绑定,这里需要注意以下几点:
(1)属性变量名称,需要跟配置中的名称一致
(2)需要提供getter和setter

如何获取自定义配置信息

通常,将自定义配置文件也放置在src/main/resource下。当然也可以创建子目录保存不同的配置,便于管理。

例如,我们在src/main/resource下创建custom目录,并添加my.properties文件,文件内容如下

=breakloop
my.age=1
my.location=BJ

读取配置信息时,需要使用@PropertySource(“classpath:custom/my.properties”)来绑定配置文件。

这里需要强调的是,网上很多版本都是使用@ConfigurationProperties进行绑定的。绑定格式如下

@ConfigurationProperties(location="classpath:custom/my.properties")
  • 1在Spring boot1.5.1之后,就废除了location参数,转而使用@PropertySource指定配置文件路径。

核心代码如下:

@RestController
@PropertySource("classpath:custom/my.properties")
public class MyConfigController {

    Logger logger= LoggerFactory.getLogger(MyConfigController.class);

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

    @Value("${my.age}")
    private int age;

    @Value("${my.location}")
    private String location;

    @RequestMapping("/getMyConfig")
    public void getMyConfig(){
        ("my name is "+name+", "+age+" years old, "+location);
    }

}

执行结果如下:

2017-12-06 11:29:16.024  INFO 9256 --- [nio-8080-exec-5] c.gemalto.configtest.MyConfigController  : my name is breakloop, 1 years old, BJ
  • 1

常见问题处理

(1)Spring Boot Annotion processor not found in classpath

需要在pom中添加dependences

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

(2)Re-run Spring Boot Configuration Annotation Processor to update generated metadata

该提示,不影响代码执行。只是提醒用户,进行必要的重新编译。再当文件进行了有效的更新时,该提示也会消失。


版权声明:本文为博主原创文章,未经博主允许不得转载。




SpringBoot工程默认读取application.properties配置文件。如果需要自定义properties文件,如何读取呢?

一、在resource中新建.properties文件

在resource目录下新建一个config文件夹,然后新建一个.properties文件放在该文件夹下。如图remote.properties所示

springboot中通过获取配置文件配置值获取配置文件中的值 springboot获取配置文件中的变量_配置文件_02

二、编写配置文件


?



remote.uploadFilesUrl=/resource/files/         


          remote.uploadPicUrl=/resource/pic/


三、新建一个配置类RemoteProperties.java


?



@Configuration         


          @ConfigurationProperties          (prefix =           "remote"          , ignoreUnknownFields =           false          )         


          @PropertySource          (          "classpath:config/remote.properties"          )         


          @Data         


          @Component         


          public          class          RemoteProperties {         


                    private          String uploadFilesUrl;         


                    private          String uploadPicUrl;         


          }


其中

@Configuration 表明这是一个配置类
@ConfigurationProperties(prefix = "remote", ignoreUnknownFields = false) 该注解用于绑定属性。prefix用来选择属性的前缀,也就是在remote.properties文件中的“remote”,ignoreUnknownFields是用来告诉SpringBoot在有属性不能匹配到声明的域时抛出异常。
@PropertySource("classpath:config/remote.properties") 配置文件路径
@Data 这个是一个lombok注解,用于生成getter&setter方法,详情请查阅lombok相关资料
@Component 标识为Bean

四、如何使用?

在想要使用配置文件的方法所在类上表上注解EnableConfigurationProperties(RemoteProperties.class)
并自动注入


?



@Autowired         


          RemoteProperties remoteProperties;


在方法中使用 remoteProperties.getUploadFilesUrl()就可以拿到配置内容了。


?



@EnableConfigurationProperties          (RemoteProperties.          class          )         


          @RestController         


          public          class          TestService{         


                    @Autowired         


                    RemoteProperties remoteProperties;         


                    


                    public          void          test(){         


                    String str = remoteProperties.getUploadFilesUrl();         


                    System.out.println(str);         


                    }         


          }


这里str就是配置文件中的”/resource/files/”了。

PS:下面看下 Spring-boot中读取config配置文件的两种方式

了解过spring-Boot这个技术的,应该知道Spring-Boot的核心配置文件application.properties,当然也可以通过注解自定义配置文件的信息。

Spring-Boot读取配置文件的方式:

一.读取核心配置文件信息application.properties的内容

     核心配置文件是指在resources根目录下的application.properties或application.yml配置文件,读取这两个配置文件的方法有两种,都比较简单。

核心配置文件application.properties内容如下:


?



test.msg=Hello World SpringBoot


方式一:使用@Value方式(常用)


?



package          Solin.controller;          


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


          import          org.springframework.web.          bind          .annotation.RequestMapping;          


          import          org.springframework.web.          bind          .annotation.RestController;          


          @RestController          


          public          class          WebController {          


                    @Value(          "${test.msg}"          )          


                    private          String          msg;          


                    @RequestMapping(          "/index1"          )           


                    public          String          index1(){          


                    return          "方式一:"          +msg;          


                    }          


          }


注意:在@Value的${}中包含的是核心配置文件中的键名。在Controller类上加@RestController表示将此类中的所有视图都以JSON方式显示,类似于在视图方法上加@ResponseBody。
访问:http://localhost:8088/index1时得到:"方式一:Hello World SpringBoot"

方式二:使用Environment方式


?



package          Solin.controller;          


          import          org.springframework.beans.factory.annotation.Autowired;          


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


          import          org.springframework.core.env.Environment;          


          import          org.springframework.web.bind.annotation.RequestMapping;          


          import          org.springframework.web.bind.annotation.RestController;          


          @RestController         


          public          class          WebController {          


                    @Autowired         


                    private          Environment env;          


                    


                    @RequestMapping          (          "/index2"          )           


                    public          String index2(){          


                    return          "方式二:"          +env.getProperty(          "test.msg"          );          


                    }          


          }


注意:这种方式是依赖注入Evnironment来完成,在创建的成员变量private Environment env上加上@Autowired注解即可完成依赖注入,然后使用env.getProperty("键名")即可读取出对应的值。
访问:http://localhost:8088/index2时得到:"方式二:Hello World SpringBoot"

二.读取自定义配置文件信息,例如:author.properties

为了不破坏核心文件的原生态,但又需要有自定义的配置信息存在,一般情况下会选择自定义配置文件来放这些自定义信息,这里在resources目录下创建配置文件author.properties

resources/author.properties内容如下:


?



=Solin          


          author.age=          22


创建管理配置的实体类:


?



package          Solin.controller;          


                    


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


          import          org.springframework.context.annotation.Configuration;          


          import          org.springframework.stereotype.Component;          


                    


          //加上注释@Component,可以直接在其他地方使用@Autowired来创建其实例对象          


          @Component         


          @ConfigurationProperties          (prefix =           "author"          ,locations =           "classpath:author.properties"          )            


          public          class          MyWebConfig{          


                    private          String name;          


                    private          int          age;          


                    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;          


                    }          


          }


注意:

    在@ConfigurationProperties注释中有两个属性:

locations:指定配置文件的所在位置
prefix:指定配置文件中键名称的前缀(我这里配置文件中所有键名都是以author.开头)

    使用@Component是让该类能够在其他地方被依赖使用,即使用@Autowired注释来创建实例。

创建测试Controller


?



package          Solin.controller;          


          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;          


          @Controller          


          public          class          ConfigController {          


                    @Autowired         


                    private          MyWebConfig conf;          


                    


                    @RequestMapping          (          "/test"          )           


                    public          @ResponseBody          String test() {          


                    return          "Name:"          +conf.getName()+          "---"          +          "Age:"          +conf.getAge();           


                    }          


          }


注意:由于在Conf类上加了注释@Component,所以可以直接在这里使用@Autowired来创建其实例对象。

访问:http://localhost:8088/test时得到:"Name:Solin---Age:22"

总结

以上所述是小编给大家介绍的在SpringBoot下读取自定义properties配置文件的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!



原文链接:


Springboot默认配置信息,都放置在application.properties文件中,位于工程目录的src/main/resource下。

springboot中通过获取配置文件配置值获取配置文件中的值 springboot获取配置文件中的变量_spring

本文记录两种方法
(1)如何获取默认配置信息
(2)如何获取自定义配置信息

常见问题
(1)Spring Boot Annotion processor not found in classpath
(2)Re-run Spring Boot Configuration Annotation Processor to update generated metadata

如何获取默认配置信息

配置信息可以通过@Value与属性变量进行绑定。

例如,在application.properties文件中定义如下变量

Test.fileName="1.txt"
path=C:/output
fileNum=1

我们在Controller中,进行变量绑定,然后打印内容。核心代码如下

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


@RestController
public class ConfigController {

    Logger logger= LoggerFactory.getLogger(ConfigController.class);

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

    @Value("${path}")
    private String path;

    @Value("${fileNum}")
    private int num;

    @RequestMapping("/getConfig")
    public void getConfig(){
        ("fileName="+name);
        ("path="+path);
        ("fileNum="+num);
    }
}

执行结果如下

2017-12-06 11:06:34.461  INFO 9504 --- [nio-8080-exec-6] com.gemalto.configtest.ConfigController  : fileName="1.txt"
2017-12-06 11:06:34.461  INFO 9504 --- [nio-8080-exec-6] com.gemalto.configtest.ConfigController  : path=C:/output
2017-12-06 11:06:34.461  INFO 9504 --- [nio-8080-exec-6] com.gemalto.configtest.ConfigController  : fileNum=1


如果配置具有相同的prefix,那么可以使用@ConfigurationProperties(prefix=”my”)进行简化绑定。

例如,我们在application.properties中添加

=breakloop1
my.age=10
my.location=BJ1

读取时,我们创建配置类MyConfigController2。

@RestController
@ConfigurationProperties(prefix="my")
public class MyConfigController2 {

    Logger logger= LoggerFactory.getLogger(MyConfigController2.class);

    private String name;

    private int age;

    private String location;

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getLocation() {
        return location;
    }

    public void setName(String name) {
         = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    @RequestMapping("/getMyConfig2")
    public void getMyConfig(){
        ("my name is "+name+", "+ age +" years old, "+location);
    }

}

执行结果如下:

2017-12-06 12:12:03.387  INFO 8504 --- [nio-8080-exec-6] c.g.configtest.MyConfigController2       : my name is breakloop1, 10 years old, BJ1
  • 1

如果不想使用@Value进行绑定,这里需要注意以下几点:
(1)属性变量名称,需要跟配置中的名称一致
(2)需要提供getter和setter

如何获取自定义配置信息

通常,将自定义配置文件也放置在src/main/resource下。当然也可以创建子目录保存不同的配置,便于管理。

例如,我们在src/main/resource下创建custom目录,并添加my.properties文件,文件内容如下

=breakloop
my.age=1
my.location=BJ
  • 1
  • 2
  • 3

读取配置信息时,需要使用@PropertySource(“classpath:custom/my.properties”)来绑定配置文件。

这里需要强调的是,网上很多版本都是使用@ConfigurationProperties进行绑定的。绑定格式如下

@ConfigurationProperties(location="classpath:custom/my.properties")
  • 1

但在Spring boot1.5.1之后,就废除了location参数,转而使用@PropertySource指定配置文件路径。

核心代码如下:

@RestController
@PropertySource("classpath:custom/my.properties")
public class MyConfigController {

    Logger logger= LoggerFactory.getLogger(MyConfigController.class);

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

    @Value("${my.age}")
    private int age;

    @Value("${my.location}")
    private String location;

    @RequestMapping("/getMyConfig")
    public void getMyConfig(){
        ("my name is "+name+", "+age+" years old, "+location);
    }

}

执行结果如下:

2017-12-06 11:29:16.024  INFO 9256 --- [nio-8080-exec-5] c.gemalto.configtest.MyConfigController  : my name is breakloop, 1 years old, BJ
  • 1

常见问题处理

(1)Spring Boot Annotion processor not found in classpath

需要在pom中添加dependences

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

(2)Re-run Spring Boot Configuration Annotation Processor to update generated metadata

该提示,不影响代码执行。只是提醒用户,进行必要的重新编译。再当文件进行了有效的更新时,该提示也会消失。