Spring Boot (5) properties参数配置

application.properties

  application.properties是spring boot默认的配置文件,spring boot默认会在以下两个路径搜索并加载这个文件

    src\main\resources

    src\main\resources\config

配置系统参数

  在application.properties中可以配置一些系统参数,spring boot会自动加载这个参数到相应的功能,如下

#端口,默认是8080
server.port=8088
#访问路径,默认为/
server.context-path=/
#输出日志文件,默认不输出
logging.file=/log.txt
#修改日志级别,默认为INFO
logging.level.root=DEBUG

自定义properties文件

  在spring boot启动类或配置类中添加以下注解,可再启动时载入自定义的配置文件

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

  如果要同时载入多个文件就用数组

@PropertySource(value={"classpath:config/a.properties","classpath:config/b.properties"})

自定义参数

key1=values1
key2=values2

然后再java代码中使用@Value注解,在项目启动时会将自定义参数加载到全局变量。

@RestController
@PropertySource("classpath:config/a.properties")
public class HelloController {

    @Value(value="${key1}")
    private String key;

    @GetMapping("/test") public String test(){ return key; } }

输入测试地址:http://localhost:8088/test 页面显示value1

批量注入到类变量

  在properties中配置两个以user为前缀的参数

user.key1=value1
user.key2=value2

  在java中用@ConfigurationProperties 将以user为前缀的参数注入到当前变量中,需要有set方法。

@RestController
@ConfigurationProperties(prefix = "user")
public class HelloController {

    public void setKey1(String key1) {
        this.key1 = key1;
    }

    @Value(value="${user.key1}") private String key1; @GetMapping("/test") public String test(){ return key1; } }

  

猜你喜欢

转载自www.cnblogs.com/baidawei/p/9104009.html
今日推荐