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

目录
  • 代码
  • 构造器绑定
  • 结合@PropertySource

代码

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 自动绑定内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • springboot @ConfigurationProperties和@PropertySource的区别

    springboot @ConfigurationProperties和@PropertySource区别 @ConfigurationProperties:寻找的是全局配置文件 @PropertySource:寻找的是指定的配置文件 理解里面有一个参数 value,可以指定很多个配置文件,所以是使用一个数组{} springboot推荐使用这种方式给容添加组件: 创建一个config包,然后在包下创建一个class 使用@bean给容器中添加组件 springboot 使用@Configura

  • SpringBoot中注解@ConfigurationProperties与@Value的区别与使用详解

    目录 注解@ConfigurationProperties 注解@Value 区别 松散语法绑定: SpEl语法表示: JSR303数据校验: 复杂类型封装: 配置文件注入值数据校验 注解@ConfigurationProperties 该注解的作用是将配置文件中配置的每一个属性的值,映射到这个组件中.@ConfigurationProperties :告诉springboot将本类中的所有属性和配置文件中相关的配置进行绑定 prefix = "person":配置文件中哪个下面的所有

  • SpringBoot @ConfigurationProperties注解的简单使用

    源码 @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ConfigurationProperties { @AliasFor("prefix") String value() default ""; @AliasFor("value") String prefix()

  • SpringBoot @ConfigurationProperties使用详解

    简介 本文将会详细讲解@ConfigurationProperties在Spring Boot中的使用. 添加依赖关系 首先我们需要添加Spring Boot依赖: <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <relativePath/> <!-- lookup

  • SpringBoot中@ConfigurationProperties 配置绑定

    SpringBoot底层的一个功能 : @ConfigurationProperties @ConfigurationProperties 配置绑定 来举一个场景例子 : 我们习惯于把经常变化的一个东西配到配置文件里面.比如把数据库的一些链接地址.账号.密码包括数据库连接池的大小等等这些属性配到properties配置文件里面,然后为了方便 , 因为我们未来可能要创建数据库连接池,我们会把这个配置文件里面的内容又一一解析到我们数据库连接池(比如javaBean我们这个对象里面),所以我们这个实现

  • springboot如何使用@ConfigurationProperties封装配置文件

    使用@ConfigurationProperties封装配置文件 业务场景: 把配置文件的信息,读取并自动封装成实体类,可以使用@ConfigurationProperties,把同类的配置信息自动封装成实体类. 1.在pom.xml中添加依赖包 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor<

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

    目录 代码 构造器绑定 结合@PropertySource 代码 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=&

  • 详解SpringBoot中自定义和配置拦截器的方法

    目录 1.SpringBoot版本 2.什么是拦截器 3.工作原理 4.拦截器的工作流程 4.1正常流程 4.2中断流程 5.应用场景 6.如何自定义一个拦截器 7.如何使其在Spring Boot中生效 8.实际使用 8.1场景模拟 8.2思路 8.3实现过程 8.4效果体验 9.总结 1.SpringBoot版本 本文基于的Spring Boot的版本是2.6.7 . 2.什么是拦截器 Spring MVC中的拦截器(Interceptor)类似于ServLet中的过滤器(Filter),它

  • SpringBoot中@ConfigurationProperties注解实现配置绑定的三种方法

    properties配置文件如下: human.name=Mr.Yu human.age=21 human.gender=male 如何把properties里面的配置绑定到JavaBean里面,以前我们的做法如下: public class PropertiesUtil { public static void getProperties(Person person) throws IOException { Properties properties = new Properties();

  • 解决springboot利用ConfigurationProperties注解配置数据源无法读取配置信息问题

    @ConfigurationProperties是springboot新加入的注解,主要用于配置文件中的指定键值对映射到一个java实体类上.那么它是怎么发挥作用的呢?下面我们将揭开@ConfigurationProperties的魔法. ConfigurationPropertiesBindingPostProcessor这个bean后置处理器,就是来处理bean属性的绑定的,这个bean后置处理器后文将称之为properties后置处理器.你需要知道以下几件事: ioc容器context的e

  • springboot中nacos-client获取配置的实现方法

    目录 1.导入nacos的maven包 2.nacos-config-spring-boot-autoconfigure解析 3.NacosConfigEnvironmentProcessor逻辑解析 在springboot中使用nacos的小伙伴是不是跟我有一样的好奇,springboot中nacos-client是怎么获取配置的?今天我跟了一下代码,大致的流程弄懂了,分享给大家. 1.导入nacos的maven包 <dependency> <groupId>com.alibab

  • 在SpringBoot中该如何配置拦截器

    拦截器也是我们经常需要使用的,在SpringBoot中该如何配置呢 拦截器不是一个普通属性,而是一个类,所以就要用到java配置方式了.在SpringBoot官方文档中有这么一段说明: 翻译: 如果你想要保持Spring Boot 的一些默认MVC特征,同时又想自定义一些MVC配置(包括:拦截器,格式化器, 视图控制器.消息转换器 等等),你应该让一个类实现 WebMvcConfigurer ,并且添加 @Configuration 注 解,但是千万不要加 @EnableWebMvc 注解.如果

  • SpringBoot中的异常处理与参数校验的方法实现

    兄弟们好,这次来跟老铁交流两个问题,异常和参数校验,在说参数校验之前我们先来说异常处理吧,因为后面参数的校验会牵扯到异常处理这块的内容. 异常处理 说到异常处理,我不知道大家有没有写过或者遇到过如下的写法. public void saveUser() { try { // 所有的业务内容,目测几百行 }catch (Exception e) { e.printStackTrace(); } } 如果出现上述的代码,里面包含了大量的业务代码,如果是你写的,赶紧改掉,不是你写的找写的,吐槽赶紧改掉

  • SpringBoot中使用redis做分布式锁的方法

    一.模拟问题 最近在公司遇到一个问题,挂号系统是做的集群,比如启动了两个相同的服务,病人挂号的时候可能会出现同号的情况,比如两个病人挂出来的号都是上午2号.这就出现了问题,由于是集群部署的,所以单纯在代码中的方法中加锁是不能解决这种情况的.下面我将模拟这种情况,用redis做分布式锁来解决这个问题. 1.新建挂号明细表 2.在idea上新建项目 下图是创建好的项目结构,上面那个parent项目是其他项目不用管它,和新建的没有关系 3.开始创建controller,service,dao(mapp

  • 在SpringBoot中,如何使用Netty实现远程调用方法总结

    Netty Netty是一个NIO客户端服务器框架: 它可快速轻松地开发网络应用程序,例如协议服务器和客户端. 它极大地简化和简化了网络编程,例如TCP和UDP套接字服务器. NIO是一种非阻塞IO ,它具有以下的特点 单线程可以连接多个客户端. 选择器可以实现单线程管理多个Channel,新建的通道都要向选择器注册. 一个SelectionKey键表示了一个特定的通道对象和一个特定的选择器对象之间的注册关系. selector进行select()操作可能会产生阻塞,但是可以设置阻塞时间,并且可

随机推荐