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

  • 相关阅读:
    调用打印预览问题
    html2canvas+Canvas2Image分享海报功能踩坑
    SQL Server – Show/Hide Results Pane in Management Studio 2012
    jQuery
    Sap PI 接口配置
    WebService 错误解决记录
    线程
    HTML和CSS
    C#高编
    MVC3
  • 原文地址:https://www.cnblogs.com/wwjj4811/p/14343262.html
Copyright © 2011-2022 走看看