63、自己建立一個Sprinboot Starter 應用
阿新 • • 發佈:2021-11-08
1.1、建立自定義的starter專案手先新增相關依賴
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies>
1.2、定義和application.yml 配置檔案繫結資料的配置類
@Data @ConfigurationProperties(prefix= "hello") public class HelloProperties { private String name; private String address; }
1.3、定義自動配置的類HelloService,將自動把這個類自動配置
public class HelloService { private String name; private String address; public HelloService(String name, String address) { this.name = name;this.address = address; } public String sayHello(){ return "你好!我的名字叫 " + name + ",我來自 " + address; } }
1.4、標註開啟自動配置 將helloProperties與配置檔案繫結,然後注入給HelloService 完成自動配置
@Configuration @EnableConfigurationProperties(HelloProperties.class) public class HelloServiceAutoConfiguration { private HelloProperties helloProperties; //通過構造方法注入配置屬性物件HelloProperties public HelloServiceAutoConfiguration(HelloProperties helloProperties) { this.helloProperties = helloProperties; } //例項化HelloService並載入Spring IoC容器 @Bean @ConditionalOnMissingBean public HelloService helloService(){ return new HelloService(helloProperties.getName(),helloProperties.getAddress()); } }
1.5、META-INF/spring.factories 建立該檔案,目的是讓spring啟動時找到這個自動配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.wcs.config.HelloServiceAutoConfiguration
2.1 使用剛才的starts 引入依賴
<dependency>
<groupId>org.wcs</groupId>
<artifactId>hello-springboot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
2.2、編寫配置類
hello:
name: edwin
address: dasdsadsa
2.3、測試是否會將編寫的配置類完成自動配置
@RestController @RequestMapping("/hello") public class HelloController { //HelloService在我們自定義的starter中已經完成了自動配置,所以此處可以直接注入 @Autowired private HelloService helloService; @GetMapping("/say") public String sayHello(){ return helloService.sayHello(); } }