zoukankan      html  css  js  c++  java
  • 02、@PropertySource指定配置文件的属性映射到JavaBean属性

    零、@PropertySource 功能类似于

    <context:property-placeholder location="classpath*:/config/load.properties"/>
    @Configuration
    @PropertySources(
            @PropertySource(value = "classpath:/config/load.properties",ignoreResourceNotFound = true,encoding = "UTF-8")
    )
    public class ServerProperties {
        @Value("${liubin.test.name}")
        private String name;
    
        public String getName() {
            return name;
        }
    }

    一、引入配置文件注解PropertySource源码

    package org.springframework.context.annotation;
    
    import ....;
    
    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Repeatable(PropertySources.class)
    public @interface PropertySource {
        String name() default "";
    
        String[] value();//可以是多个
    
        boolean ignoreResourceNotFound() default false;
    
        String encoding() default "";
    
        Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class;
    }

    二、PropertySources中
    包含多个PropertySource
    package org.springframework.context.annotation;
    
    import java.lang.annotation.Documented;
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface PropertySources {
        PropertySource[] value();
    }

    三、引入配置文件后配置项被@Value注解使用

    @Component
    @PropertySource("classpath:teacher.properties")
    public class Student {
    
        @Value("${name}")
        private String name;
    
        @Value("${age}")
        private int age;
    
        @Value("${sex}")
        private String sex;
    
        @Value("${height}")
        private int height;
    
        @Value("${weight}")
        private int weight;
    }

    四、引入配置文件后配置项被Spring Boot 的@ConfigurationProperties使用,一站式注入到相应的JavaBean的所有属性中

    @PropertySource({"classpath:teacher.properties"}) //指定某配置文件,无此参数则在默认全局配置文件中获取
    @Component
    @ConfigurationProperties(prifix=“teacher”) //配置文件中前缀名为teacher的配置项的所有属性都映射到此JavaBean中
    public class Teacher {
        private String name;
    
        private int age;
    
        private String sex;
    
        private int height;
    
        private int weight;
    
      getset方法
    }

    五、不同的属性配置文件中若有相同的配置项,写在后面配置文件中的属性覆盖前面的

    @PropertySources(
        {
            @PropertySource("classpath:teacher.properties")
        }
    )
  • 相关阅读:
    基于opencv的摄像头的标定
    图像的角点简介
    周转时间和平均带权时间等
    QT各个版本的下载的地址
    参考文献格式
    sublime中的emmet插件的使用技巧
    sublime快捷键
    CSS布局居中
    Markdown 语法说明(简体中文版)
    sql作业题
  • 原文地址:https://www.cnblogs.com/guchunchao/p/9853118.html
Copyright © 2011-2022 走看看