场景启动器只是说明这个场景有多少个依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
点进去这个场景才可以看到它里面配置的依赖信息
1.我们先new 一个空的项目 springboot-starter
2.我们在这个空项目里创建一个maven工程 名字叫hello-hlq-spring-boot-starter
3.我们再创建一个springInit..的项目名字叫做hello-hlq-spring-boot-starter-autoconfigure
功能配置都在这个里面
4。我们在hello-hlq-spring-boot-starter这个项目里面把hello-hlq-spring-boot-starter-autoconfigure引入进来
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.hlq</groupId> <artifactId>hello-hlq-spring-boot-starter</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>com.hlq</groupId> <artifactId>hello-hlq-spring-boot-starter-autoconfigure</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> </dependencies> </project>
5.加入我们有一个HelloService这个组件经常使用
5.1 我们可以先写一个HelloService一个这个类,它里面有一个方法会用到HelloProperties里 的属性,但是不要给他放在容器里面
5.2我们再写一个HelloProperties类标上@ConfigurationProperties("hlq.hello")
5.3 我们再写一个自动配置类HelloServiceAutoConfiguration,让它根据条件给容器中注册组件
//默认不要放在容器中 public class HelloService { @Autowired HelloProperties helloProperties; public String sayHello(String name){ return helloProperties.getPrefix() + name + helloProperties.getSuffix(); } } ======================================================================================= @ConfigurationProperties("hlq.hello") public class HelloProperties { // private String prefix; //su 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; } } ====================================================================================== @ConditionalOnMissingBean(HelloService.class)//这个也可以写到方法上,写到方法上我们可以自定义这个组件 @EnableConfigurationProperties(HelloProperties.class)//与配置文件绑定 默认放在容器中 @Configuration public class HelloServiceAutoConfiguration { @Bean public HelloService helloService(){ HelloService helloService = new HelloService(); return helloService; } }
关键一步,在resources下面创建一个META-INF/spring.factories中 EnableAutoConfiguration 的值,使得项目启动加载指定的自动配置类
#auto config org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.hlq.springboot.hello.auto.HelloServiceAutoConfiguration
6.最后一步,先把我们的hello-hlq-spring-boot-starter-autoconfigure这个项目进行clean
然后install 把它下载到本地仓库里
再把hello-hlq-spring-boot-starter进行同样操作
7.测试:
创建一个web项目,引入依赖就可以使用了