SpringBoot运行原理

1、查看当前项目已启用和未启用自动配置 在application.properties中设置属性

debug=true

2、自动配置满足两个条件 ①配置参数
②配置Bean
3、自己写一个自动配置 ①新建一个Maven项目

SpringBoot运行原理
文章图片
image
②pom.xml
4.0.0com.example.springboot 09-springboot-autoconfig 0.0.1-SNAPSHOT09-springboot-autoconfighttp://www.example.com【SpringBoot运行原理】UTF-8 1.7 1.7 org.springframework.boot spring-boot-autoconfigure 2.1.3.RELEASE junit junit 4.12 test maven-clean-plugin 3.1.0 maven-resources-plugin 3.0.2 maven-compiler-plugin 3.8.0 maven-surefire-plugin 2.22.1 maven-jar-plugin 3.0.2 maven-install-plugin 2.5.2 maven-deploy-plugin 2.8.2 maven-site-plugin 3.7.1 maven-project-info-reports-plugin 3.0.0

③属性配置
package com.example.springboot; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "hello") public class HelloServiceProperties1 { private static final String MSG = "world"; private String msg = MSG; public String getMsg() { return msg; }public void setMsg(String msg) { this.msg = msg; } }

④判断依据类
package com.example.springboot; public class HelloService { private String msg; public String sayHello() { return "Hello" + msg; } public String getMsg() { return msg; }public void setMsg(String msg) { this.msg = msg; } }

⑤自动配置类
package com.example.springboot; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @EnableConfigurationProperties(HelloServiceProperties1.class) @ConditionalOnClass(HelloService.class) @ConditionalOnProperty(prefix = "hello",value = "https://www.it610.com/article/enabled",matchIfMissing = true) public class HelloServiceAutoConfiguration {@Autowired private HelloServiceProperties1 helloServiceProperties; @Bean @ConditionalOnMissingBean(HelloService.class) public HelloService helloService() { HelloService helloService = new HelloService() ; helloService.setMsg(helloServiceProperties.getMsg()); return helloService; } }

⑥自动配置
在src/main/resources新建META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.example.springboot.HelloServiceAutoConfiguration

若有多个配置,用“,”隔开
⑦新建springboot项目,在pom.xml添加依赖
com.example.springboot 09-springboot-autoconfig 0.0.1-SNAPSHOT

运行代码
@Autowired HelloService helloService; @RequestMapping("/index1") publicString index1() { return helloService.sayHello(); }

    推荐阅读