zoukankan      html  css  js  c++  java
  • Spring:@ConfigurationProperties配置绑定

    @ConfigurationProperties + @Component

    在 Spring Boot 项目中,我们可以将大量的参数配置在 application.properties 或 application.yml 文件中,通过 @ConfigurationProperties 注解,我们可以方便的获取这些参数值

    @ConfigurationProperties:prefix===>属性的前缀

    /**
     * @Author wem.jie
     * @Description 只有容器中的组件才拥有SpringBoot强大功能
     * @Date 2021/1/29 8:43
     **/
    @Data
    @Component
    @ConfigurationProperties(prefix = "wj.person")
    public class Person {
        private String personName;
        private Integer age;
    }
    

    配置文件

    wj.person.personName=wen.jie
    wj.person.age=18
    

    主启动类:

    @SpringBootApplication
    public class Boot2TestApplication {
    
        public static void main(String[] args) {
            ConfigurableApplicationContext run =
                    SpringApplication.run(Boot2TestApplication.class, args);
    
            Person person = run.getBean(Person.class);
            System.out.println(person);
        }
    
    }
    

    image-20210129085418998

    @EnableConfigurationProperties +@ConfigurationProperties

    @Data
    @ConfigurationProperties(prefix = "wj.person")
    public class Person {
        private String personName;
        private Integer age;
    }
    

    在配置类上面加上@EnableConfigurationProperties

    //开启Person配置绑定功能
    //把Person组件自动注册到容器中
    @EnableConfigurationProperties(Person.class)
    @SpringBootApplication
    public class Boot2TestApplication {
    
        public static void main(String[] args) {
            ConfigurableApplicationContext run =
                    SpringApplication.run(Boot2TestApplication.class, args);
    
            Person person = run.getBean(Person.class);
            System.out.println(person);
        }
    }
    

    image-20210129093459773

    宽松绑定

    以下配置,无论哪一种都会被绑定到对象属性上。

    wj.person.personName=wen.jie
    wj.person.person-Name=wen.jie
    wj.person.person_Name=wen.jie
    wj.person.personname=wen.jie
    wj.person.PERSON-name=wen.jie
    

    自动提示

    引入依赖

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

    然后重新启动应用后,以后写配置文件,自定义的都有提示了。

    image-20210129131126278

  • 相关阅读:
    读完此文让你了解各个queue的原理
    借汇编之力窥探String背后的数据结构奥秘
    汇编高手带你玩转字符串,快上车!
    语雀调研
    产品技能一:抽象能力
    我所认知的敏捷开发
    产品经理需要的技能,我有吗?
    孙正义采访:接下来的30年,一切将被重新定义
    5G小白鼠
    goto语句为啥不受待见
  • 原文地址:https://www.cnblogs.com/wwjj4811/p/14343262.html
Copyright © 2011-2022 走看看