当下Java Web开发领域,毫无疑问SpringBoot已经只手遮天。 没有SpringBoot之前,如果我们要搭建一个Spring Web应用,要多繁杂有多繁杂,折腾半天,也不能能搭建一个可运行的应用。我们需要做:配置Servlet、配置IOC、配置tomcat等等以及随处可见的各种xml,反正是烦的很。 有了Spring Boot之后,就少了很多XML配置,而且注解也是特别的简单,我们就不需要更多额外的关注,可以专注编码。 在使用Spring Boot之后,效率上大大的提高了。Spring Boot也发现了很多Starter模块,比如spring-boot-starter-web、spring-boot-starter-tomcat、spring-boot-starter-test等等,让我们可以开箱即用! Spring Boot具有这么多的优点,在面试中也是必问知识之一。比如面试官问你:如何自己写一个starter,供其他人使用呢? 要回答这个问题,首先我们需要弄明白starter是个什么东西?你可以理解它是一个可插拔式的插件。通过starter,能够简化之前繁杂的配置,它帮助我们整合需要的配置和依赖,统一集成到starter中,再通过自动装配生成Bean,注入Spring容器中供我们使用。 弄明白starter是什么,接下来我们一起动手搞一个starter试试看看。 1、引入spring-boot-autoconfigure2、编写供其他服务使用的服务类MyStarterServicepackage com.harry.game.rts.server; /** * @author harry * @date 2022-01-27 5:50 PM */ public class MyStarterService { private String name; private String pwd; /** * */ public String say() { return "my name is " + name; } public MyStarterService(String name, String pwd) { this.name = name; this.pwd = pwd; } public MyStarterService() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } } 3、用@ConfigurationProperties将application.xml中的属性映射为配置类 package com.harry.game.rts.server; import org.springframework.boot.context.properties.ConfigurationProperties; /** * @author harry * @date 2022-01-27 5:54 PM */ @ConfigurationProperties(prefix = "my-starter.service") public class MyStarterServiceProperties { private String name; private String pwd; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } } 4、自动装配类MyStarterServiceAutoConfigurationpackage com.harry.game.rts.server; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author harry * @date 2022-01-27 5:58 PM */ @Configuration @ConditionalOnClass(MyStarterService.class) @EnableConfigurationProperties(MyStarterServiceProperties.class) public class MyStarterServiceAutoConfiguration { @Bean public MyStarterService myStarterService(MyStarterServiceProperties properties) { return new MyStarterService(properties.getName(),properties.getPwd()); } } 5、在src->main->java->resource目录下建META-INF文件夹,放spring.factories文件,文件内容如下: org.springframework.boot.autoconfigure.EnableAutoConfiguration= com.harry.game.rts.server.MyStarterServiceAutoConfiguration 至此,一个starter就已经完成了! org.springframework.boot spring-boot-autoconfigure