springboot学习之创建自己的starter

时间:2022-12-26 22:34:31

之前在springboot学习之Starter中提到springboot官方提供了很多starter来实现自动配置,简化我们的开发,那么我们能不能把自己常用的一些组件也封装成一个starter来进行自动配置呢?答案是可以的,只要按照springboot自动配置的模式来写,就可以实现自己的starter,其实蛮简单的,下面我们来写一个简单的starter

pom.xml

<?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.peng</groupId>
    <artifactId>helloword-spring-boot-starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>helloword-spring-boot-starter</name>
    <description>Demo project for Spring Boot</description>


    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>1.5.4.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

创建属性类

@ConfigurationProperties(prefix = "datasource")
public class DataSource {

  private String driver;
  private String url;
  private String userName;
  private String passWord;

  public String getDriver() {
    return driver;
  }

  public void setDriver(String driver) {
    this.driver = driver;
  }

  public String getUrl() {
    return url;
  }

  public void setUrl(String url) {
    this.url = url;
  }

  public String getUserName() {
    return userName;
  }

  public void setUserName(String userName) {
    this.userName = userName;
  }

  public String getPassWord() {
    return passWord;
  }

  public void setPassWord(String passWord) {
    this.passWord = passWord;
  }
}

创建服务类

public class DataSourceService {

  private DataSource dataSource;

  public DataSourceService(DataSource dataSource){
    this.dataSource = dataSource;
  }

  public String getDriver(){
    return dataSource.getDriver();
  }

  public String getUrl(){
    return dataSource.getUrl();
  }

  public String getUserName(){
    return dataSource.getUserName();
  }

  public String getPassWord(){
    return dataSource.getPassWord();
  }

}

创建自动配置类

@Configuration
@EnableConfigurationProperties(DataSource.class)
@ConditionalOnClass(DataSourceService.class)
@ConditionalOnProperty(prefix = "datasource",value = "enable",matchIfMissing = true)
public class DataSourceAutoConfiguration {

  @Autowired
  private DataSource dataSource;

  @Bean
  @ConditionalOnMissingBean(DataSourceService.class)
  public DataSourceService dataSourceService(){
    DataSourceService dataSourceService = new DataSourceService(dataSource);
    return dataSourceService;
  }

}

说明:
@Configuration 表示当前是一个配置类
@EnableConfigurationProperties(DataSource.class) 表示开启DataSource类的配置
@ConditionalOnClass(DataSourceService.class) 表示当DataSourceService这个类在类路径中时,且当前容器中没有这个Bean的情况下,开始自动配置
@ConditionalOnProperty(prefix = “datasource”,value = “enable”,matchIfMissing = true) 表示指定的属性是否有指定的值

在resources/META-INF目录下创建spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.peng.DataSourceAutoConfiguration

至此,一个自定义的starter基本上已经完成了,下面是测试

执行mvn clean install命令,将starter安装到本地仓库中

新建一个springboot项目来测试一下我们自定义的starter

pom.xml文件中引用我们自已写的starter

<?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.example</groupId>
    <artifactId>starter-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>starter-demo</name>
    <description>Demo project for Spring Boot</description>


    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
        <relativePath/>
    </parent>


    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.peng</groupId>
            <artifactId>helloword-spring-boot-starter</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>


</project>

添加属性到属性文件application.properties中

datasource.driver=oracle.jdbc.driver.OracleDriver
datasource.url=jdbc:oracle:thin:@localhost:1521:orcl
datasource.userName=root
datasource.passWord=123

编写Controller类

@RestController
@SpringBootApplication
public class StarterDemoApplication {

    @Autowired
    DataSourceService dataSourceService;

    @GetMapping("get/driver")
    public String getDriver(){
        return dataSourceService.getDriver();
    }

    @GetMapping("get/url")
    public String getUrl(){
        return dataSourceService.getUrl();
    }

    public static void main(String[] args) {
        SpringApplication.run(StarterDemoApplication.class, args);
    }
}

在属性文件中加入debug=true,然后运行程序,可以看到所有自动配置的详细信息:

========================= AUTO-CONFIGURATION REPORT
========================= 

Positive matches:
----------------- 
   ## 可以看到自定义的starter已经包含在启动信息中,说明我们自己写的自动配置生效了
   DataSourceAutoConfiguration#dataSourceService matched:
      - @ConditionalOnMissingBean (types: com.peng.DataSourceService; SearchStrategy: all) did not find any beans (OnBeanCondition) 
   DispatcherServletAutoConfiguration matched:
      - @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)       - @ConditionalOnWebApplication (required) found StandardServletEnvironment (OnWebApplicationCondition) 
   DispatcherServletAutoConfiguration.DispatcherServletConfiguration matched:
      - @ConditionalOnClass found required class 'javax.servlet.ServletRegistration'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)       - Default DispatcherServlet did not find dispatcher servlet beans (DispatcherServletAutoConfiguration.DefaultDispatcherServletCondition)       ...
      ...下面省略
      ...

在浏览器中输入:http://localhost:8080/get/url 可以看到配置的datasource.url信息
至此,我们自己的starter就完成了!!!