• springboot中properties|yml文件属性注入方式,@ConfigurationProperties、@Value("${value.name}");@Configuration 和 @Component 区别


    看到@value取值的类上经常有@ConfigurationProperties注解,就想删掉,详细区分记录一下。

    一、配置文件值 .yml文件

    (复制请注意:后加空格)

    test:
      name: high
      age: 22
    student:
      lulu:
        names: name-lulu
        ages: 7

    二、属性注入 @ConfigurationProperties方式

    @Setter
    @Getter
    @Component
    @ConfigurationProperties(prefix = "test")
    public class PropVal {
    
        private String name;
        private String age;
    
        @PostConstruct
        public void peek() {
            System.out.println(name + " - " + age);
        }
    }

    详解@ConfigurationProperties实现原理与实战

    使用示例:@ConfigurationProperties的使用

    三、属性注入 SPEL 方式

    @Setter
    @Getter
    @Component
    public class propValue {
    
        @Value("${test.name}")
        private String name;
        
        @Value("${test.age}")
        private String age;
    
        @PostConstruct
        public void peek() {
            System.out.println(name + " = " + age);
        }
    }

    四、使用@Configuration + @Bean方式

    @Configuration
    public class ProppertValue {
    
        @Bean
        @ConfigurationProperties(prefix = "student.lulu")
        public Student stu() {
            return new Student();
        }
    
        @Autowired
        private Student stu;
    
        public ProppertValue() {
            System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        }
    
        @PostConstruct
        public void peek() {
            System.out.println(stu);
        }
    }
    
    
    /**
    需要注入属性的类,可以注入属性名称相同的字段。
    */
    
    @Data
    public class Student {
    
        private String names;
        private int ages;
    }

    所有相关控制台日志:

    high - 22
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Student(names=name-lulu, ages=7)
    high = 22

    五、@PostConstruct

    @PostConstruct注解好多人以为是Spring提供的。其实是Java自己的注解。

    Java中该注解的说明:@PostConstruct该注解被用来修饰一个非静态的void()方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。

    该注解的方法在整个Bean初始化中的执行顺序:

    Constructor(构造方法) ----- @Autowired(依赖注入) ----- @PostConstruct(注释的方法) 

    通常用来完成一些在构造器中无法完成或不适合在构造器中完成的初始化。

    如上,只是为了方便,peek一眼注入结果。

    上个网上偷的图

    六、@Configuration 和 @Component 区别

    @ConfigurationProperties 注解使用姿势,这一篇就够了

    Spring @Configuration 和 @Component 区别

     

    .

  • 相关阅读:
    【分治】洛谷试炼场
    【Manacher】Colorful String
    【动态规划】背包九讲及相应习题
    【算法课】最大间隙问题
    【hash】Similarity of Subtrees
    YBT 股票买卖
    YBT 鸡蛋的硬度
    YBT 电池的寿命
    YBT Ride to Office
    YBT 装箱问题
  • 原文地址:https://www.cnblogs.com/foolash/p/13818313.html
Copyright © 2020-2023  润新知