从零搭建开发脚手架 SpringBoot自定义配置的多种姿势及Idea自动提示

背景

日常开发中,经常会使用到自定义配置,例如在常用的application.yml中增加配置,在命令行中进行配置覆盖,以及外部的自定义xxx.properties等。

  • 如果是工程管理的配置,IDEA会自动提示框架的相关配置,防止我们写错配置项。
  • 我们也常使用自定义外部文件配置,用来管理一些项目中重要的秘钥、证书等。

获取配置方式

假设在application.yml或者application.properties存在自定义配置。

laker:
  username: laker

方式一:@Value注解

@Component
public class LakerBean {
    @Value("${laker.username}")
    private String username;

}

方式二:@ConfigurationProperties注解(建议)

@Configuration //将该Bean放入spring容器中
@Data
@ConfigurationProperties(prefix = "laker") // 指定前缀
public class TestConfig {
    private String username;
    private String password;
}

@Component
public class LakerBean {
    @Autowired
    TestConfig testConfig ;
}

方式三:Environment接口

@Component
public class LakerBean {
    @Autowired
    Environment env;
    ...
    env.getProperty("laker.username")
}

大部分场景我们建议使用@ConfigurationProperties注解方式获取配置。

自定义配置文件laker.properties

除了默认的application.yml配置文件,还支持自定义配置文件。例如新建个laker.properties

laker.username=laker
laker.password=123

我们使用的是@PropertySource注解。

注意:

  • 只支持propertiesxml格式文件,不支持yml格式
  • 支持classpathfileclasspath:app.properties or file:/path/to/file.xml.
@Data
@Configuration
@ConfigurationProperties(prefix = "laker", ignoreUnknownFields = true) 
@PropertySource("classpath:laker.properties")//指定配置文件位置
public class TestConfig {
    private String username;
    private String password;
}

自定义配置文件laker.yml

如果想自定义支持yml格式,只需要增加个自定义PropertySourcesPlaceholderConfigurer如下。

@Configuration
public class LakerYml {
    @Bean
    public static PropertySourcesPlaceholderConfigurer loadYaml(){
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        //yaml.setResources(new FileUrlResource("/config/laker.yml"));
        yaml.setResources(new ClassPathResource("laker.yml"));
        configurer.setProperties(Objects.requireNonNull(yaml.getObject()));
        return configurer;
    }
}

其他同上面的laker.properties,@PropertySource("classpath:laker.yml"),指定配置文件位置.

laker.yml

laker:
  username: laker

IDEA自动提示功能

非常重要,如果没有这个自动提示,那么很容易写错配置项。

1.添加依赖

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

2.添加配置类

@Configuration //将该Bean放入spring容器中
@Data
@ConfigurationProperties(prefix = "laker") // 指定前缀
public class TestConfig {
    /**
     * 用户名
     */
    private String username;
    /**
     * 密码
     */
    private String password;
}

3.在application.yml中测试自动提示

注意:要重新编译项目,会在target\classes\META-INF目录生成spring-configuration-metadata.json文件。

我们在application.yml中输入laker效果如下:

注意:对于上面我们自定义的laker.yml默认是没有提示的,我们需要把自定义配置文件加入到SpringBoot工程环境即可。

选择项目结构把自定义文件加入到config files中,然后保存-应用。

原理

以下内容来自:https://blog.csdn.net/u013202238/article/details/117407129

依赖spring-boot-configuration-processor,其作用能够解析我们的配置类,生成spring-configuration-metadata.json文件

  • 扫描以@ConfigurationProperties 注解的类

  • 如果我们不添加该依赖,按照同样的格式、文件名称手写编写这个json文件,也可以实现提示功能

  • SpringBoot给我们规定了名为additional-spring-configuration-metadata.json的文件,便于我们手动编写一些特殊的配置项,在生成json文件里面的内容时,会将additional-spring-configuration-metadata.json里面的内容追加到spring-configuration-metadata.json

SpringBoot只是给出了json格式的配置文件,由Idea插件读取该文件实现提示,而且只有idea Ultimate版本才会有这个功能,Community社区版本无法提示。当然eclipse中也有插件可以来实现配置项的自动提示。

spring-boot-configuration-processor工作原理
在自动生成配置提示的json文件时,最后一步就是编译项目。就是为了让spring-boot-configuration-processor执行,其实就是利用了java的编译时期的spi扩展机制。javax.annotation.processing.Processor(注解处理器)

注解处理器(Annotation Processor)是javac内置的一个用于编译时扫描和处理注解(Annotation)的工具,在程序编译阶段工作,所以我们可以在编译期间通过注解处理器进行我们需要的操作。

比较常用的用法就是在编译期间获取相关注解数据,然后动态生成.java源文件(让机器帮我们写代码),通常是自动产生一些有规律性的重复代码,解决了手工编写重复代码的问题,大大提升编码效率。

实际上我们常用的Lombok这个jar,通过@Getter/@Setter生成字段的getter/setter方法也是利用了同样的原理.

配置优先级

Spring Boot能从多种属性源获得属性,包括

  • 命令行参数(–server.port=9000)
  • java:comp/env里的JNDI属性
  • Java 系统属性(System.getProperties())
  • 操作系统环境变量
  • RandomValuePropertySource 配置的 random.* 属性值
  • 配置文件(application-{profile}.properties和YAML变体)
  • 配置文件(YAML 文件、Properties 文件)
  • 通过@PropertySource标注的属性源
  • 默认属性

这个列表按照优先级排序,也就是说,任何在高优先级属性源里设置的属性都会覆盖低优先级的相同属性。例如,命令行参数会覆盖其他属性源里的属性。

配置文件(YAML 文件、Properties 文件)说明

SpringBoot启动会扫描以下位置的application.properties/yml文件作为spring boot的默认配置文件:

file:./config/
file:./
classpath:/config/
classpath:/
  • 外置,在相对于应用程序运行目录的/config子目录里。
  • 外置,在应用程序运行的目录里。
  • 内置,在config包内。
  • 内置,在Classpath根目录。

同样,这个列表按照优先级排序。也就是说,/config子目录里的application.properties会覆盖应用程序Classpath里的application.properties中的相同属性。
此外,如果你在同一优先级位置同时有application.properties和application.yml,那么application.yml里的属性会覆盖application.properties里的属性

yml > yaml > properties

以上只列了常用的外部配置,具体请参考SpringBoot官方文档。

参考

  • https://blog.csdn.net/u013202238/article/details/117407129

  • https://docs.spring.io/spring-boot/docs/2.4.5/reference/html/appendix-configuration-metadata.html#configuration-metadata-providing-manual-hints

  • https://docs.spring.io/spring-boot/docs/2.4.5/reference/html/spring-boot-features.html#boot-features-external-config

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lakernote

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值