場景:抽取聊天機器人場景,它可以打招呼。 效果:任何項目導入此 starter
都具有打招呼功能,并且問候語中的人名需要可以在配置文件中修改。
- 創建自定義 starter 項目,引入 spring-boot-starter 基礎依賴。
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>
- 編寫模塊功能,引入模塊所有需要的依賴。
- 編寫 xxxAutoConfiguration 自動配置類,幫其他項目導入這個模塊需要的所有組件。
- 編寫配置文件 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports指定啟動需要加載的自動配置。
- 其他項目引入即可使用
業務代碼
@Service
public class RobotService {@AutowiredRobotProperties robotProperties;public String sayHello(){return "hello"+robotProperties.getName()+":"+robotProperties.getAge()+"郵箱"+robotProperties.getEmail();}
}
寫下面代碼為了進行屬性綁定,配置文件(application.properties)配了什么屬性項這個類里面都可以直接進行綁定關聯(在配置文件中寫的數據通過這個配置文件,在業務代碼中引入RobotProperties robotProperties并進行自動注入,就會通過這個來獲取配置文件中的屬性)
@ConfigurationProperties(prefix = "robot")
@Component
@Data
public class RobotProperties {private String name;private String age;private String email;
}
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional>
</dependency>
基本抽取
-
創建starter項?,把公共代碼需要的所有依賴導? 把公共代碼復制進來
不選場景
引入需要的web包<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional> </dependency>
刪除主程序類
在新項目中導入該starter
- ??寫?個 RobotAutoConfiguration ,給容器中導?這個場景需要的所有組件
為什么這些組件默認不會掃描進去?
starter所在的包和 引?它的項?的主程序所在的包不是??層級
- 別?引?這個 starter ,直接導?這個 RobotAutoConfiguration ,就能把這個場景的組件導?進來
使用@EnableXxx機制
完全自動配置
- 依賴SpringBoot的SPI機制
- META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
?件中編寫好我們?動配置類的全類名即可 - 項?啟動,?動加載我們的?動配置類