虽然spring boot 会给使用者准备很多的starter,但是在某些情况还是需要开发一些公共的相关功能,去让团队其他人使用。
一、启动原理想要其他人引用starter,就需要一个场景启动器。如:
org.springframework.boot spring-boot-starter-web
场景启动器,只是引入一些该场景下使用的依赖,然后引入自动配置 autoconfigure。自动配置包引入所有启动器都引用的 spring-boot-starter
二、自定义starter1、创建两个项目,一个启动器,一个自动装配 :
启动器中引入自动装配:
4.0.0 org.example mg-hello-spring-boot-starter1.0-SNAPSHOT com.mg mg-hello-spring-boot-start-autoconfigure0.0.1-SNAPSHOT
在自动装配中编写提供功能、自动装配属性类、自动装配类
提供功能:
package com.mg.service;
import org.springframework.beans.factory.annotation.Autowired;
public class HelloService {
@Autowired
HelloProperties helloProperties;
public String sayHello(String userName){
return helloProperties.getPrefix() + ":" + userName + "》" + helloProperties.getSuffix();
}
}
配置类:
package com.mg.service;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("mg.hello")
public class HelloProperties {
private String prefix;
private String suffix;
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
}
自动装配:
package com.mg.service.auto;
import com.mg.service.HelloProperties;
import com.mg.service.HelloService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConditionalOnMissingBean(HelloService.class)
@EnableConfigurationProperties(HelloProperties.class)
public class HelloServiceAutoConfigurtion {
@Bean
public HelloService helloService(){
HelloService helloService = new HelloService();
return helloService;
}
}
PS:pom文件中不要引入maven打包插件,否则其引入的时候,无法import功能类
安装到本地仓库即可。
在另一个项目中引入:
org.example mg-hello-spring-boot-starter1.0-SNAPSHOT
编写业务类:
package com.wjf.boot.controller;
import com.mg.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Autowired
HelloService helloService;
@GetMapping("/")
public String hello(){
return helloService.sayHello("张三");
}
}
配置文件:
mg.hello.prefix = WJF mg.hello.suffix = LMR
运行后可以看到:
三、spring boot 原理1、启动过程
- 创建SpringApplication
- 保存相关信息
- 判断当前应用的类型 - servlet
- bootstrappers 初始启动引导器 从spring.factories中寻找 org.springframework.Bootstrapper
- 在spring.factories寻找初始化器,ApplicationContextInitializer
- 在spring.factories寻找监听器,ApplicationListener
- 运行SpringApplication



