一、starte详解:
1、starter场景启动器:
SpringBoot-starter是一个集成接合器,主要完成两件事:
(1)、引入模块所需的相关jar包
(2)、自动配置各自模块所需的属性
注:
spring-boot-starter-*:官方提供
*-spring-boot-starter:第三方提供
2、starter实现原理:
(1)、首先,SpringBoot在启动时会先去依赖的starter包中寻找 resources/META-INF/spring.factories 文件,然后根据文件中配置的Jar包去扫描项目所依赖的Jar包
(2)、然后,根据 spring.factories 配置加载自动配置类。
(3)、最后,根据 @Conditional 注解的条件,进行自动配置,并将Bean注入Spring Context上下文当中。
二、Springboot自动配置原理:
Springboot启动的时候会通过@EnableAutoConfiguration注解找到配置文件中的所有自动配置类(XxxxAutoConfiguration类),并对其进行加载,而这些自动配置类都是以AutoConfiguration结尾来命名的,它实际上就是一个JavaConfig形式的Spring容器配置类,它能通过以Properties结尾命名的类中取得在全局配置文件中配置的属性如:server.port,而XxxxProperties类是通过@ConfigurationProperties注解与全局配置文件中对应的属性进行绑定的。
三、手写一个starter:
手写一个starter。功能很简单,调用starter内对象的一个方法输出”xxx,hello! xxx”
1、hello-spring-boot-starter工程:
(1)、改POM:
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.7.1
com.iven
hello-spring-boot-starter
0.0.1-SNAPSHOT
hello-spring-boot-starter
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-configuration-processor
true
org.springframework.boot
spring-boot-autoconfigure
org.projectlombok
lombok
1.18.20
org.apache.maven.plugins
maven-compiler-plugin
3.10.1
8
8
(2)、编写业务类Service:
@Data
@AllArgsConstructor //全参构造
@NoArgsConstructor //无参构造
public class HelloService {
private String name;
private String detail;
public String hello() {
return getName()+",hello! " + getDetail();
}
}
(3)、编写Configuration配置类(主):
@Configuration //表明这是一个springBoot的配置类
public class HelloConfig {
@Value("${com.hello:Iven}")
private String name;
@Value("${com.hello:冲冲冲}")
private String detail;
@Bean //将对象放入IOC容器中,对象名就是方法名
public HelloService helloService(){
return new HelloService(name,detail);
}
}
(4)、编写spring.factories文件:
为了让springboot容器扫描到配置类,建一个resource目录,一个META-INF文件夹和spring.factories文件
#等号后面是配置类的全路径(包+配置类名)
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.iven.hellospringbootstarter.config.HelloConfig
(5)、install打包到本地仓库;
2、test-starter-demo工程:
(1)、添加依赖:
com.iven
hello-spring-boot-starter
0.0.1-SNAPSHOT
(2)、使用:
@RestController
@RequestMapping("/v1")
public class control {
@Autowired
private HelloService helloService;
@RequestMapping("")
public String demo(){
helloService.setName("Pitt");
return helloService.hello();
}
}
搜索
复制
Original: https://www.cnblogs.com/Iven-L/p/16592159.html
Author: 爱文(Iven)
Title: 9、手写一个starter
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/575691/
转载文章受原作者版权保护。转载请注明原作者出处!