利用 Spring Boot 中的 @ConfigurationProperties,优雅绑定配置参数

使用 @Value(“${property}”) 注释注入配置属性有时会很麻烦,尤其是当你使用多个属性或你的数据是分层的时候。

Spring Boot 引入了一个可替换的方案 —— @ConfigurationProperties 来注入属性。

JavaBean 属性绑定

@Data
@ConfigurationProperties("my.service")
public class MyProperties {

    // 我们可以简单地用一个值初始化一个字段来定义一个默认值
    private boolean enabled = true;

    private InetAddress remoteAddress;

    private final Security security = new Security();

    @Data
    public static class Security {

        private String username;

        private String password;
        // 如果这个属性配置的话,默认是"USER"
        private List roles = new ArrayList<>(Collections.singleton("USER"));

    }
}

在配置文件中进行如下配置:

my:
  service:
    enabled: true
    remoteAddress: 127.0.0.1
    security:
     username: csx
     password: passwoed
     roles:
       - role1
       - role2

最后生成的 Bean 的属性如下:

{
  "enabled": true,
  "remoteAddress": "127.0.0.1",
  "security": {
    "username": "csx",
    "password": "passwoed",
    "roles": [
      "role1",
      "role2"
    ]
  }
}

以上的绑定当时需要提供默认的构造函数,以及get/setter方法。
并且不支持 JavaBean 中的静态成员变量的数据绑定

另外,@ConfigurationProperties 还有两个其他属性。

@ConfigurationProperties( value = "my.service",
                          ignoreInvalidFields = false,
                          ignoreUnknownFields = false)

ignoreInvalidFields:是否忽略非法值,比如将一个字符串 “foo” 赋值给 bool 值,不忽略的话会报启动异常。

ignoreUnknownFields:对于多余的配置是否会报异常。

构造函数绑定

有些情况下,我们需要绑定的 JavaBean 是不可变的(防止配置注入 Bean 以后,开发者在程序中错误地将配置改掉了)。这种情况下我们可以使用构造函数形式的绑定,只提供 getter 方法。

@Getter
@ConstructorBinding
@ConfigurationProperties("my.service")
public class MyProperties {

    private boolean enabled;
    private InetAddress remoteAddress;
    private final Security security;

    public MyProperties(boolean enabled, InetAddress remoteAddress, Security security) {
        this.enabled = enabled;
        this.remoteAddress = remoteAddress;
        this.security = security;
    }

    @Getter
    public static class Security {

        private String username;
        private String password;
        private List roles;

        public Security(String username, String password, @DefaultValue("USER") List roles) {
            this.username = username;
            this.password = password;
            this.roles = roles;
        }
    }
}

@DefaultValue 可以指定默认值。

使用构造函数绑定的方式,只能 @EnableConfigurationProperties 或者 @ConfigurationPropertiesScan 的方式激活 Bean。而不能使用 @Component、@Bean 或者 @Import 的方式进行数据绑定。

如果你的类有多个构造函数,可以直接指定使用哪个。

@ConstructorBinding
public MyProperties(boolean enabled, InetAddress remoteAddress, Security security) {
    this.enabled = enabled;
    this.remoteAddress = remoteAddress;
    this.security = security;
}

激活方式

方式一:添加 @Component 注解

上面的方式需要保证 MyProperties 能被 Spring 扫到。

@Data
@Component
@ConfigurationProperties("my.service")
public class MyProperties {

}

方式二:通过 @Bean 方法

@Configuration
public class ServiceConfig {

    @Bean
    public MyProperties myProperties(){
        return new MyProperties();
    }
}

方式三:@EnableConfigurationProperties(推荐)

@Configuration
@EnableConfigurationProperties(MyProperties.class)
public class ServiceConfig {

}

方式四:@ConfigurationPropertiesScan

@SpringBootApplication
@ConfigurationPropertiesScan({ "com.example.app", "com.example.another" })
public class MyApplication {

}

怎么使用

我们通过配置在 Spring 容器中生成了配置 Bean,那么需要怎么使用他们呢?

@Service
public class MyService {
    // 依赖注入
    @Autowired
    private MyProperties properties;

    public void service(){
        System.out.println(properties.getRemoteAddress());
    }

}

@Service
public class MyService {

    private MyProperties properties;
    // 通过构造函数注入,一般推荐这种方式
    public MyService(MyProperties properties) {
        this.properties = properties;
    }

    public void service(){
        System.out.println(properties.getRemoteAddress());
    }

}

给第三方类绑定值

假如某些类不是你自己开发的,你也想使用 @ConfigurationProperties 的方式给他绑定值,那么可以进行下面的方式进行配置。

@Configuration(proxyBeanMethods = false)
public class ThirdPartyConfiguration {

    @Bean
    @ConfigurationProperties(prefix = "another")
    public AnotherComponent anotherComponent() {
        return new AnotherComponent();
    }

}

宽松绑定原则(Relaxed Binding)

所谓的宽松绑定原则是指:并不是 JavaBean 中的属性必须要和配置文件中的一致才能绑定数据,context-path 也能绑定到 contextPath 属性上。下面举个列子:

@ConfigurationProperties(prefix = "my.main-project.person")
public class MyPersonProperties {

    private String firstName;

    public String getFirstName() {
        return this.firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

}

下面的几种方式,都能将配置文件或者环境变量中的值绑定到 firstName 上。

形式 使用场景 my.main-project.person.first-name

推荐使用在 .properties

and .yml

files. my.main-project.person.firstName

Standard camel case syntax. my.main-project.person.first_name

推荐使用在 .properties

and .yml

files. MY_MAINPROJECT_PERSON_FIRSTNAME

推荐使用在系统环境变量读取配置时使用

和 @Value 对比

@Value 是 Spring Framework 中的注解,而 @ConfigurationProperties 是在 Spring Boot 中引入的。

利用 Spring Boot 中的 @ConfigurationProperties,优雅绑定配置参数

参考

Original: https://www.cnblogs.com/54chensongxia/p/15250479.html
Author: 程序员自由之路
Title: 利用 Spring Boot 中的 @ConfigurationProperties,优雅绑定配置参数

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/541898/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • 工程师什么时机最合适选择跳槽?

    先聊一下跳槽这个事。在 Java 工程师的职业生涯中,跳槽几乎是我们每一位工程师都会经历的事情。但在面试前需要考虑清楚:现在到底应不应该跳槽? class Resume { pub…

    Java 2023年6月13日
    066
  • json-lib-2.4.jar Bug,json字符串中value为”[value]”结构时,解析为数组,不会解析成字符串

    使用json-lib.jar 2.4进行json字符串转换为对象时发现一个bug。贴下测试代码: net.sf.json-lib json-lib 2.4 jdk15 com.al…

    Java 2023年6月7日
    080
  • Elasticsearch的cmd窗口乱码问题(windows)

    elasticsearch 7.6.0 windows版日志乱码问题解决 修改jvm.options,如何重启es即可 新增 -Dfile.encoding=GBK Origina…

    Java 2023年6月16日
    065
  • Java面试题

    包含的模块 本文分为十九个模块,分别是:Java 基础、容器、多线程、反射、对象拷贝、Java Web 、异常、网络、设计模式、Spring/Spring MVC、Spring B…

    Java 2023年5月29日
    063
  • HashMap之resize()方法(一)

    404. 抱歉,您访问的资源不存在。 可能是网址有误,或者对应的内容被删除,或者处于私有状态。 代码改变世界,联系邮箱 contact@cnblogs.com 园子的商业化努力-困…

    Java 2023年6月9日
    058
  • fastposter v2.8.1 发布 电商海报生成器

    fastposter v2.8.1 发布 电商海报生成器 fastposter海报生成器,电商海报编辑器,电商海报设计器,fast快速生成海报 海报制作 海报开发。二维码海报,图片…

    Java 2023年6月5日
    071
  • THO医鸣会章程

    404. 抱歉,您访问的资源不存在。 可能是网址有误,或者对应的内容被删除,或者处于私有状态。 代码改变世界,联系邮箱 contact@cnblogs.com 园子的商业化努力-困…

    Java 2023年5月29日
    046
  • java-单例详解

    一. 什么是单例模式 因程序需要,有时我们只需要某个类同时保留一个对象,不希望有更多对象,此时,我们则应考虑单例模式的设计。 二. 单例模式的特点 单例模式只能有一个实例。 单例类…

    Java 2023年6月8日
    070
  • spring*.xml配置文件明文加密

    系统架构:spring+mvc(Oracle是用jdbc自己封装的接口) 1.数据库配置文件加密 原xml配置 ….. 加密实现过程 思路:继承DruidDataSource,…

    Java 2023年6月8日
    071
  • Spring类加载初始化Bean链路

    1.spring类加载 AbstractApplicationContext.finishBeanFactoryInitialization(…); beanFactory.p…

    Java 2023年5月30日
    058
  • Java8新特性1:接口中方法

    回顾之前《JavaSE-23.2》:https://www.cnblogs.com/yppah/p/14874992.htmlhttps://www.cnblogs.com/ypp…

    Java 2023年6月5日
    088
  • 测试用例千万不能随便,记录由一个测试用例异常引起的思考

    一 测试用例大家平时写不写? 我以前写测试用例只是针对业务接口,每个接口写一个,数据case也只是测一种。能跑通就可以了。要不同的场景case,那就改数据。重新跑一遍。简单省事。 …

    Java 2023年6月8日
    077
  • Typora

    404. 抱歉,您访问的资源不存在。 可能是网址有误,或者对应的内容被删除,或者处于私有状态。 代码改变世界,联系邮箱 contact@cnblogs.com 园子的商业化努力-困…

    Java 2023年5月29日
    067
  • Servlet 4

    Servlet 4.0规约简介 Servlet 4.0 规约是JCP组织定义的Web规约,JSR编号369。 1.1 什么是Servlet? Servlet 是基于Java技术的W…

    Java 2023年6月15日
    067
  • Aviator——轻量级Java表达式求值引擎

    简介 Aviator是一个高性能、轻量级的java语言实现的表达式求值引擎,主要用于各种表达式的动态求值。现在已经有很多开源可用的java表达式求值引擎,为什么还需要Avaitor…

    Java 2023年5月29日
    078
  • 【转】Java的三种代理模式

    Java的三种代理模式 1.代理模式 代理(Proxy)是一种设计模式,提供了对目标对象另外的访问方式;即通过代理对象访问目标对象.这样做的好处是:可以在目标对象实现的基础上,增强…

    Java 2023年5月29日
    073
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球