Welcome to my website, have a nice day!
Dream it, Do it, Make it!

Spring Boot通过注解读取配置文件内容的几种方式?

Spring为我们提供的从配置文件中读取配置信息的方式主要有以下几种。

示例配置文件:application.yml,内容如下:

wuhan2020: 2020年初武汉爆发了新型冠状病毒,疫情严重,但是,我相信一切都会过去!武汉加油!中国加油!

my-profile:
  name: Guide哥
  email: [email protected]

library:
  location: 湖北武汉加油中国加油
  books:
    - name: 天才基本法
      description: 二十二岁的林朝夕在父亲确诊阿尔茨海默病这天,得知自己暗恋多年的校园男神裴之即将出国深造的消息——对方考取的学校,恰是父亲当年为她放弃的那所。
    - name: 时间的秩序
      description: 为什么我们记得过去,而非未来?时间“流逝”意味着什么?是我们存在于时间之内,还是时间存在于我们之中?卡洛·罗韦利用诗意的文字,邀请我们思考这一亘古难题——时间的本质。
    - name: 了不起的我
      description: 如何养成一个新习惯?如何让心智变得更成熟?如何拥有高质量的关系? 如何走出人生的艰难时刻?

方式一 通过@Value注解,读取比较简单的配置信息

在类属性上添加注解,如下:

@Value("${wuhan2020}")
String wuhan2020;

需要注意的是 @value这种方式是不被推荐的,Spring 比较建议的是下面几种读取配置信息的方式。

方式二 通过@ConfigurationProperties注解使用,封装到Bean中

2.1 @ConfigurationProperties注解使用

比如,读取上面配置文件示例的library相关信息,可以定义一个LibraryProperties类,专门用于封装library相关信息。

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@ConfigurationProperties(prefix = "library")
@Setter
@Getter
@ToString
class LibraryProperties {
    private String location;
    private List<Book> books;

    @Setter
    @Getter
    @ToString
    static class Book {
        String name;
        String description;
    }
}

注意: LibraryProperties类,使用了@Component注解,这样就可以在具体业务类中,通过注入的方式,使用这个配置文件信息类。

这种方式的使用方式如下:

package cn.javaguide.readconfigproperties;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author shuang.kou
 */
@SpringBootApplication
public class ReadConfigPropertiesApplication implements InitializingBean {

    private final LibraryProperties library;

    public ReadConfigPropertiesApplication(LibraryProperties library) {
        this.library = library;
    }

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

    @Override
    public void afterPropertiesSet() {
        System.out.println(library.getLocation());
        System.out.println(library.getBooks());    }
}

方式三 通过@ConfigurationProperties注解和@EnableConfigurationProperties注解配置使用

这种方式在配置文件信息封装类定义中,不使用方式二中提及的@Component注解,而是在使用对应配置文件信息的类中,使用@EnableConfigurationProperties注解,对对应属性进行注册使用。

3.1 使用示例

配置信息Bean:

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;

/**
* @author shuang.kou
*/
@Getter
@Setter
@ToString
@ConfigurationProperties("my-profile")
@Validated
public class ProfileProperties {
   @NotEmpty
   private String name;

   @Email
   @NotEmpty
   private String email;

   //配置文件中没有读取到的话就用默认值
   private Boolean handsome = Boolean.TRUE;

}

具体使用类:

package cn.javaguide.readconfigproperties;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

/**
 * @author shuang.kou
 */
@SpringBootApplication
@EnableConfigurationProperties(ProfileProperties.class)
public class ReadConfigPropertiesApplication implements InitializingBean {
    private final ProfileProperties profileProperties;

    public ReadConfigPropertiesApplication(ProfileProperties profileProperties) {
        this.profileProperties = profileProperties;
    }

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

    @Override
    public void afterPropertiesSet() {
        System.out.println(profileProperties.toString());
    }
}

注意具体使用类前的@EnableConfigurationProperties注解。

3.2 @ConfigurationProperties注解功能扩展

使用@ConfigurationProperties注解读取配置文件时,还可以对相关属性值进行校验内容是否合法,比如邮箱格式的校验。代码见3.1中配置信息Bean的email属性。

方式四 使用@PropertySource注解方式使用,直接读取指定 properties 文件

如下:

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:website.properties")
@Getter
@Setter
class WebSite {
    @Value("${url}")
    private String url;
}

使用:

@Autowired
private WebSite webSite;

System.out.println(webSite.getUrl());//https://javaguide.cn/

配置文件使用扩展:Spring加载配置文件的优先级

Spring读取配置文件也是有优先级的:

Spring读取配置文件优先级

Refferences

  1. Spring 如何优雅读取配置文件?
赞(0)
未经允许禁止转载:Ddmit » Spring Boot通过注解读取配置文件内容的几种方式?

评论 抢沙发

登录

找回密码

注册