SpringBoot 自动装配

前言

我们都会用Springboot,例如使用redis,首先引入依赖,然后yml文件中进行配置,第三步,使用RedisTemplate类,就可以使用了。看起来就这么简单。

其实越简单的的东西,在背后越是有复杂的逻辑帮助我们实现了具体的细节。

 

1.demo

看个小demo(github访问不了,就不上传项目了)

第一个工程代码

 1 package com.auto.spring.my;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
 5 import org.springframework.boot.context.properties.EnableConfigurationProperties;
 6 import org.springframework.context.annotation.Bean;
 7 import org.springframework.context.annotation.Configuration;
 8 
 9 @Configuration
10 @EnableConfigurationProperties({MyProperty.class})
11 public class CustomAutoConfiguration {
12 
13     @Autowired
14     private MyProperty myProperty;
15 
16     @Bean
17     @ConditionalOnMissingBean
18     public MyPro myPro(){
19         MyPro myPro = new MyPro();
20         if (myProperty.getName() != null) {
21             myPro.setName(myProperty.getName());
22         } else {
23             myPro.setName("缺失姓名");
24         }
25         myPro.setAge(77);
26 
27         if (myProperty.getGender() != null) {
28             myPro.setGender(myProperty.getGender());
29         } else {
30             myPro.setGender("缺失姓名");
31         }
32 
33         return myPro;
34     }
35 }
View Code
 1 package com.auto.spring.my;
 2 
 3 import lombok.Data;
 4 
 5 @Data
 6 public class MyPro {
 7 
 8     private String name;
 9 
10     private Integer age;
11 
12     private String gender;
13 }
View Code
 1 package com.auto.spring.my;
 2 
 3 import lombok.Data;
 4 import org.springframework.boot.context.properties.ConfigurationProperties;
 5 
 6 @ConfigurationProperties(prefix = "custom")
 7 @Data
 8 public class MyProperty {
 9 
10     private String name;
11 
12     private Integer age;
13 
14     private String gender;
15 }
View Code
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.auto.spring.my.CustomAutoConfiguration
spring.factories

上述四个文件,亲测可以使用.

再新建一个项目,引入第一个工程的依赖,配置custom.name  和 custom.gender就可以使用了。

 

2.原理

QA1:如何实现自动装配?

QA2:如何实现按需加载?

 

 整理出一个纲要。下次有利于回忆。

 

3.实战分析

 

posted @ 2022-12-03 17:17  Mr.袋鼠  阅读(25)  评论(0编辑  收藏  举报