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

  • 相关阅读:
    Java内存模型原理,你真的理解吗?
    CentOS 7.4 下搭建 Elasticsearch 6.3 搜索群集
    CentOS 7下ElasticSearch集群搭建案例
    分布式系统理论基础
    分布式系统理论进阶
    Paxos,Raft,Zab一致性协议-Raft篇
    P2P 网络核心技术:Gossip 协议
    分布式系统Paxos算法
    Hacker News的热门排名算法(转)
    Elasticsearch分布式机制和document分析
  • 原文地址:https://www.cnblogs.com/wwjj4811/p/14343262.html
Copyright © 2011-2022 走看看