天天看点

飞5的Spring Boot2(4)- 自定义starter

飞5的Spring Boot2(4)- 自定义starter

自定义starter​

在业务中,我们经常需要一些常用的工具包,现在,有了Spring Boot,我们可以使用starter的方式引入。

新建maven工程,在pom.xml中加入Spring Boot依赖

1<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot -->
2        <dependency>
3            <groupId>org.springframework.boot</groupId>
4            <artifactId>spring-boot</artifactId>
5            <version>2.0.1.RELEASE</version>
6        </dependency>      

由于starter项目需要使用到spring的一些特性,因此在starter项目中至少需要依赖一个对org.springframework.boot的依赖。

三步构建

第一步

创建一个maven项目user-starter,创建UserService类,代码如下:

1public class UserService {
2    public void helloStarter(){
3        System.out.println(">> hello starter");
4    }
5}      

第二步

创建一个UserAutoConfiguration类,代码如下:

1import org.springframework.context.annotation.Bean;
2import org.springframework.context.annotation.Configuration;
3@Configuration
4public class UserAutoConfiguration {
5    @Bean
6    public UserService dbCountRunner() {
7        return new UserService();
8    }
9}      

加入配置

在resources目录中创建META-INF文件夹,然后在META-INF文件夹中创建spring.factories文件==,这个文件用于告诉spring boot去找指定的自动配置文件。在应用程序启动过程中,spring boot使用springfactoriesloader类加载器查找org.springframework.boot.autoconfigure.enableautoconfiguration关键字对应的java配置文件。spring boot会遍历在各个jar包种meta-inf目录下的spring.factories文件,构建成一个配置文件链表。

spring.factories内容如下:

1org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.cloud.skyme.UserAutoConfiguration      

加入依赖

在项目中进行依赖

1<dependency>
2    <groupId>com.eju.ess</groupId>
3    <artifactId>user-starter</artifactId>
4    <version>0.0.2-SNAPSHOT</version>
5</dependency>      
1import org.springframework.beans.factory.annotation.Autowired;
 2import org.springframework.web.bind.annotation.RequestMapping;
 3import org.springframework.web.bind.annotation.RestController;
 4import com.cloud.skyme.UserService;
 5import lombok.extern.slf4j.Slf4j;
 6@Slf4j
 7@RestController
 8public class SampleController {
 9    @Autowired
10    private UserService t=null;
11    @RequestMapping("/")
12    String home() {
13        t.helloStarter();
14        return "Hello World!";
15    }
16}      

继续阅读