Spring Boot获取配置文件值

JAVA学习网 2019-01-25 07:55:03

在程序开发过程中,经常会将一些可能会修改的值放到配置文件中,那么在Spring Boot中,如何获取配置的文件的值呢?

本篇博客就讲解下使用@Value注解或者@ConfigurationProperties注解来获取配置文件值的方法

方式1:使用@Value注解获取配置文件值

首先在application.yml中添加如下配置:

book:
  author: wangyunfei
  name: spring boot

然后修改Spring Boot项目启动类的代码如下:

package com.zwwhnly.springbootdemo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class SpringbootdemoApplication {

    @Value("${book.author}")
    private String bookAuthor;
    @Value("${book.name}")
    private String bookName;

    @RequestMapping("/")
    String index() {
        return "book name is:" + bookName + " and book author is:" + bookAuthor;
    }

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

启动项目,在浏览器输入http://localhost:8080/,会看到如下信息:

方式2:使用@ConfigurationProperties注解获取配置文件值

在方式1中,我们使用@Value注解来获取配置文件值,但如果多个地方都需要获取的话,就需要在多个地方写注解,造成混乱,不好管理,

其实,Spring Boot还提供了@ConfigurationProperties注解来获取配置文件值,该种方式可把配置文件值和一个Bean自动关联起来,使用起来更加方便,个人建议用这种方式。

在application.yml中添加如下配置:

author:
  name: wangyunfei
  age: 32

新建类AuthorSettings,添加@Component和@ConfigurationProperties注解

package com.zwwhnly.springbootdemo;

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

@Component
@ConfigurationProperties(prefix = "author")
public class AuthorSettings {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

修改启动类代码如下:

package com.zwwhnly.springbootdemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class SpringbootdemoApplication {

    @Autowired
    private AuthorSettings authorSettings;

    @RequestMapping("/")
    String index() {
        return "book name is:" + authorSettings.getName() + " and book author is:" + authorSettings.getAge();
    }

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

启动项目,在浏览器输入http://localhost:8080/,会看到如下信息:

阅读(2401) 评论(0)