使用eclipse在springboot中读取自定义配置并自动提示


自定义一些配置属性的时候,也希望像达到像Springboot中自动提示一样的效果,无论是自己配置还是交接给别人都颇为方便。

1. 实现配置自动装配首先使用注解@ConfigurationProperties,该注解参数为要配置的属性的前缀

如配置属性为test.name,表示不同的服务器上有特殊的名字,注解为

@ConfigurationProperties("test")

2. 实现一个实体类,类的属性名称必须与外部属性的名称匹配,类的属性必须有set函数,spring通过set方法注入属性值。没有的话,无法自动装配。

也可以使用@Data注解,简化代码,@Data注解已为类提供了 equals()、hashCode()、toString() 方法。

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

@Configuration
@ConfigurationProperties("test")
public class TestConfig {
    /**服务器名字**/
    private String name;
    
    public String getName() {
        return name;
    }

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

}

3. 配置文件中加上配置

test.name=zs

有上面三步就可以实现配置属性自动装配

4. 如果要实现在配置文件中自动提示属性值,还需要引入spring-boot-configuration-processor依赖。

 

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

在@ConfigurationProperties中也提示了推荐添加spring-boot-configuration-processor依赖

引入依赖之后,通过maven再Update Project,在target\classes\META-INF文件下会生成配置属性的元文件

 

该文件中对属性进行了描述

 

在配置文件中使用test配置时,就可以自动提示属性和注释

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM