SpringBoot中@ConfigurationProperties实现配置自动绑定的方法

 更新时间:2022年02月16日 14:42:25   作者:ITKaven  
本文主要介绍了SpringBoot中@ConfigurationProperties实现配置自动绑定的方法,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

代码

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.2</version>
    </parent>

    <packaging>jar</packaging>

    <groupId>com.kaven</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <name>springboot</name>
    <description>springboot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

配置类:

package com.kaven.springboot.config;

import lombok.Setter;
import lombok.ToString;

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

import java.util.List;
import java.util.Map;
import java.util.Set;

@ConfigurationProperties(prefix = "user")
@Setter
@ToString
public class UserProperties {
    private String username;
    private String password;
    private Set<String> hobbies;
    private Map<String, Integer> scores;
    private List<UserToken> userToken;
}

UserToken类:

package com.kaven.springboot.config;

import lombok.Setter;
import lombok.ToString;

@Setter
@ToString
public class UserToken {
    private String token;
}

接口:

package com.kaven.springboot.controller;

import com.kaven.springboot.config.UserProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class ConfigController {
    @Resource
    private UserProperties userProperties;

    @GetMapping("/config")
    public String getConfig() {
        return userProperties.toString();
    }
}

application.properties

user.username="kaven"
user.password="itkaven"
user.hobbies[0]="A"
user.hobbies[1]="B"
user.hobbies[2]="C"
user.scores.mathematics=145
user.scores.english=80
user.user-token[0].token="A"
user.user-token[1].token="B"
user.user-token[2].token="C"

启动类:

package com.kaven.springboot;

import com.kaven.springboot.config.UserProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@SpringBootApplication
@EnableConfigurationProperties(value = {UserProperties.class})
//@ConfigurationPropertiesScan(basePackageClasses = {UserProperties.class})
public class SpringbootApplication {
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(SpringbootApplication.class);
        application.run(args);
    }
}

下面这两个注解都可以使得Spring Boot基于被@ConfigurationProperties注解修饰的类创建bean,因此UserProperties实例可以自动注入到控制器中。

@EnableConfigurationProperties(value = {UserProperties.class})
@ConfigurationPropertiesScan(basePackageClasses = {UserProperties.class})

@ConfigurationPropertiesScan注解还可以指定要被扫描的包数组。

@ConfigurationPropertiesScan(basePackages = {"com.kaven.springboot.config"})

启动应用,访问http://localhost:8080/config

在这里插入图片描述

效果符合预期。

构造器绑定

Spring Boot将配置文件中的配置自动绑定到配置类,无非就是通过反射等手段,创建配置类实例,而配置项需要绑定到配置类实例的属性,这一般通过属性的set方法或者构造器来实现,上面的演示是通过set方法来进行绑定,这是@Setter注解的效果。

@Setter

如果需要通过构造器将配置项绑定到配置类实例的属性,可以使用@ConstructorBinding注解。

package com.kaven.springboot.config;

import lombok.ToString;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConstructorBinding;

import java.util.List;
import java.util.Map;
import java.util.Set;

@ConfigurationProperties(prefix = "user")
@ToString
@ConstructorBinding
public class UserProperties {
    private String username;
    private String password;
    private Set<String> hobbies;
    private Map<String, Integer> scores;
    private List<UserToken> userToken;

    public UserProperties(String username,
                          String password,
                          Set<String> hobbies,
                          Map<String, Integer> scores,
                          List<UserToken> userToken) {
        this.username = username;
        this.password = password;
        this.hobbies = hobbies;
        this.scores = scores;
        this.userToken = userToken;
    }
}

使用@ConstructorBinding注解修饰类的问题在于类中可能有多个构造器,如果出现这种情况就会有问题。

package com.kaven.springboot.config;import lombok.ToString;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.boot.context.properties.ConstructorBinding;import java.util.List;import java.util.Map;import java.util.Set;@ConfigurationProperties(prefix = "user")@ToString@ConstructorBindingpublic class UserProperties {<!--{cke_protected}{C}%3C!%2D%2D%20%2D%2D%3E--> private String username; private String password; private Set<String> hobbies; private Map<String, Integer> scores; private List<UserToken> userToken; public UserProperties() {<!--{cke_protected}{C}%3C!%2D%2D%20%2D%2D%3E-->} public UserProperties(String username, String password, Set<String> hobbies, Map<String, Integer> scores, List<UserToken> userToken) {<!--{cke_protected}{C}%3C!%2D%2D%20%2D%2D%3E--> this.username = username; this.password = password; this.hobbies = hobbies; this.scores = scores; this.userToken = userToken; }}

因为Spring Boot不知道调用哪个构造器。

在这里插入图片描述

可以将@ConstructorBinding注解修饰在构造器上。

package com.kaven.springboot.config;

import lombok.ToString;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConstructorBinding;

import java.util.List;
import java.util.Map;
import java.util.Set;

@ConfigurationProperties(prefix = "user")
@ToString
public class UserProperties {
    private String username;
    private String password;
    private Set<String> hobbies;
    private Map<String, Integer> scores;
    private List<UserToken> userToken;

    public UserProperties() {}

    @ConstructorBinding
    public UserProperties(String username,
                          String password,
                          Set<String> hobbies,
                          Map<String, Integer> scores,
                          List<UserToken> userToken) {
        this.username = username;
        this.password = password;
        this.hobbies = hobbies;
        this.scores = scores;
        this.userToken = userToken;
    }
}

在这里插入图片描述

结合@PropertySource

SourceConfig类:

package com.kaven.springboot.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource(value = "classpath:/static/user.properties")
public class SourceConfig {}

在这里插入图片描述

在这里插入图片描述

效果符合预期,@ConfigurationProperties实现配置自动绑定就介绍到这里,,更多相关SpringBoot @ConfigurationProperties 自动绑定内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java实现去除ArrayList重复字符串

    java实现去除ArrayList重复字符串

    本文主要介绍了java实现去除ArrayList重复字符串,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-09-09
  • IDEA 单元测试报错:Class not found:xxxx springboot的解决

    IDEA 单元测试报错:Class not found:xxxx springb

    这篇文章主要介绍了IDEA 单元测试报错:Class not found:xxxx springboot的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-01-01
  • 解析Java编程之Synchronized锁住的对象

    解析Java编程之Synchronized锁住的对象

    这篇文章主要介绍了解析Java编程之Synchronized锁住的对象,具有一定参考价值,需要的朋友可以了解下。
    2017-10-10
  • Sparsearray稀疏数组原理及实例详解

    Sparsearray稀疏数组原理及实例详解

    这篇文章主要介绍了Sparsearray稀疏数组原理及实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-05-05
  • Java 反射机制详解及实例代码

    Java 反射机制详解及实例代码

    本文主要介绍Java 反射机制的知识,这里提供示例代码帮助大家学习理解此部分知识,有需要的小伙伴可以参考下
    2016-09-09
  • Netty网络编程实战之搭建Netty服务器

    Netty网络编程实战之搭建Netty服务器

    Netty是JBOSS开源的一款NIO网络编程框架,可用于快速开发网络的应用。Netty是一个异步的、基于事件驱动的网络应用框架,用于快速开发高性能的服务端和客户端。本文将详细说说如何搭建Netty服务器,需要的可以参考一下
    2022-10-10
  • Spring Cloud实现远程调用OpenFeign组件的方法

    Spring Cloud实现远程调用OpenFeign组件的方法

    本文主要介绍了SpringCloud中实现远程调用的组件OpenFeign的相关知识与操作,包括OpenFeign的介绍、快速上手、参数传递和最佳实践,感兴趣的朋友跟随小编一起看看吧
    2026-02-02
  • Springboot整合quartz实现多个定时任务实例

    Springboot整合quartz实现多个定时任务实例

    这篇文章主要介绍了Springboot整合quartz实现多个定时任务代码实例,Quartz 是一款功能强大的开源任务调度框架,几乎可以集成到任何 Java 应用程序中,Quartz 可用于创建简单或复杂的任务调度,用以执行数以万计的任务,需要的朋友可以参考下
    2023-08-08
  • Java中的分布式锁与同步锁使用详解

    Java中的分布式锁与同步锁使用详解

    这篇文章主要介绍了Java中的分布式锁与同步锁使用详解,在分布式系统中,由于存在多个节点并行执行任务,可能会出现竞争条件和数据不一致的问题,分布式锁通过约束同一时刻只有一个节点能够获得锁的方式,确保了对共享资源的独占访问,需要的朋友可以参考下
    2023-07-07
  • java引用jpython的方法示例

    java引用jpython的方法示例

    这篇文章主要介绍了java引用jpython的方法,结合实例形式分析了java引用jpython及相关使用技巧,需要的朋友可以参考下
    2016-11-11

最新评论