自定义spring boot starter

Spring Boot由众多Starter组成,随着版本的推移Starter家族成员也与日俱增。在传统Maven项目中通常将一些层、组件拆分为模块来管理,以便相互依赖复用,在Spring Boot项目中我们则可以创建自定义Spring Boot Starter来达成该目的。

接下来,我们演示如何创建一个spring boot starter。

先创建一个Maven项目并引入依赖,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.example</groupId>
    <artifactId>example-spring-boot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <!-- Import dependency management from Spring Boot -->
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>1.5.2.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

这里说下artifactId的命名问题,Spring 官方 Starter通常命名为spring-boot-starter-{name}spring-boot-starter-webSpring官方建议非官方Starter命名应遵循{name}-spring-boot-starter的格式。

这里讲一下我们的Starter要实现的功能,很简单,提供一个Service,包含一个能够将字符串加上前后缀的方法String wrap(String word)

public class ExampleService {

    private String prefix;
    private String suffix;

    public ExampleService(String prefix, String suffix) {
        this.prefix = prefix;
        this.suffix = suffix;
    }
    public String wrap(String word) {
        return prefix + word + suffix;
    }
}

前缀、后缀通过读取application.properties(yml)内的参数获得

@ConfigurationProperties("example.service")
public class ExampleServiceProperties {
    private String prefix;
    private String suffix;
    //省略 getter setter

重点,编写AutoConfigure

@Configuration
@ConditionalOnClass(ExampleService.class)
@EnableConfigurationProperties(ExampleServiceProperties.class)
public class ExampleAutoConfigure {

    @Autowired
    private ExampleServiceProperties properties;

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(prefix = "example.service",value = "enabled",havingValue = "true")
    ExampleService exampleService (){
        return  new ExampleService(properties.getPrefix(),properties.getSuffix());
    }

}

解释下用到的几个和Starter相关的注解:

  • @ConditionalOnClass,当classpath下发现该类的情况下进行自动配置。
  • @ConditionalOnMissingBean,当Spring Context中不存在该Bean时。
  • @ConditionalOnProperty(prefix = "example.service",value = "enabled",havingValue = "true"),当配置文件中example.service.enabled=true时。

更多相关注解,建议阅读官方文档该部分

最后一步,在resources/META-INF/下创建spring.factories文件,内容供参考下面~

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.autocinfigure.ExampleAutoConfigure

OK,完事,运行 mvn:install打包安装,一个Spring Boot Starter便开发完成了。

创建一个Spring Boot项目来 试试~

引入example-spring-boot-starter依赖

<dependency>
    <groupId>com.example</groupId>
    <artifactId>example-spring-boot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>
 </dependency>

创建application.properties,进行配置

example.service.enabled=true
example.service.prefix=####
example.service.suffix=@@@@

创建一个简单的Spring Web Application,注入Starter提供的ExampleService看它能否正常工作~

@SpringBootApplication
@RestController
public class Application {

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

    @Autowired
    private ExampleService exampleService;

    @GetMapping("/input")
    public String input(String word){
        return exampleService.wrap(word);
    }

}

启动Application,访问/input接口试试看~

总结下Starter的工作原理

  1. Spring Boot在启动时扫描项目所依赖的JAR包,寻找包含spring.factories文件的JAR包
  2. 根据spring.factories配置加载AutoConfigure
  3. 根据 @Conditional注解的条件,进行自动配置并将Bean注入Spring Context

最后,列一些常用的starter:

应用启动器  
1spring-boot-starter这是Spring Boot的核心启动器,包含了自动配置、日志和YAML。 
2spring-boot-starter-actuator帮助监控和管理应用。 
3spring-boot-starter-amqp通过spring-rabbit来支持AMQP协议(Advanced Message Queuing Protocol)。 
4spring-boot-starter-aop支持面向方面的编程即AOP,包括spring-aop和AspectJ。 
5spring-boot-starter-artemis通过Apache Artemis支持JMS的API(Java Message Service API)。 
6spring-boot-starter-batch支持Spring Batch,包括HSQLDB数据库。 
7spring-boot-starter-cache支持Spring的Cache抽象。 
8spring-boot-starter-cloud-connectors支持Spring Cloud Connectors,简化了在像Cloud Foundry或Heroku这样的云平台上连接服务。 
9spring-boot-starter-data-elasticsearch支持ElasticSearch搜索和分析引擎,包括spring-data-elasticsearch。 
10spring-boot-starter-data-gemfire支持GemFire分布式数据存储,包括spring-data-gemfire。 
11spring-boot-starter-data-jpa支持JPA(Java Persistence API),包括spring-data-jpa、spring-orm、Hibernate。 
12spring-boot-starter-data-mongodb

支持MongoDB数据,包括spring-data-mongodb。

 
13spring-boot-starter-data-rest通过spring-data-rest-webmvc,支持通过REST暴露Spring Data数据仓库。 
14spring-boot-starter-data-solr支持Apache Solr搜索平台,包括spring-data-solr。 
15spring-boot-starter-freemarker支持FreeMarker模板引擎。 
16spring-boot-starter-groovy-templates支持Groovy模板引擎。 
17spring-boot-starter-hateoas通过spring-hateoas支持基于HATEOAS的RESTful Web服务。 
18spring-boot-starter-hornetq

通过HornetQ支持JMS。

 
19spring-boot-starter-integration支持通用的spring-integration模块。 
20spring-boot-starter-jdbc

支持JDBC数据库。

 
21spring-boot-starter-jersey支持Jersey RESTful Web服务框架。 
22spring-boot-starter-jta-atomikos通过Atomikos支持JTA分布式事务处理。 
23spring-boot-starter-jta-bitronix通过Bitronix支持JTA分布式事务处理。 
24spring-boot-starter-mail

支持javax.mail模块。

 
25spring-boot-starter-mobile支持spring-mobile。 
26spring-boot-starter-mustache

支持Mustache模板引擎。

 
27spring-boot-starter-redis支持Redis键值存储数据库,包括spring-redis。 
28spring-boot-starter-security支持spring-security。 
29spring-boot-starter-social-facebook支持spring-social-facebook 
30spring-boot-starter-social-linkedin支持pring-social-linkedin 
31spring-boot-starter-social-twitter支持pring-social-twitter 
32spring-boot-starter-test支持常规的测试依赖,包括JUnit、Hamcrest、Mockito以及spring-test模块。 
33spring-boot-starter-thymeleaf支持Thymeleaf模板引擎,包括与Spring的集成。 
34spring-boot-starter-velocity支持Velocity模板引擎。 
35spring-boot-starter-web支持全栈式Web开发,包括Tomcat和spring-webmvc。 
36spring-boot-starter-websocket支持WebSocket开发。 
37spring-boot-starter-ws支持Spring Web Services。 
 应用启动器面向生产环境  
1spring-boot-starter-actuator

增加了面向产品上线相关的功能,比如测量和监控。

 
2spring-boot-starter-remote-shell增加了远程ssh shell的支持。 
 应用启动器还有一些替换技术的启动器  
1spring-boot-starter-jetty引入了Jetty HTTP引擎(用于替换Tomcat)。 
2spring-boot-starter-log4j支持Log4J日志框架。 
3spring-boot-starter-logging引入了Spring Boot默认的日志框架Logback。 
4spring-boot-starter-tomcat引入了Spring Boot默认的HTTP引擎Tomcat。 
5spring-boot-starter-undertow

引入了Undertow HTTP引擎(用于替换Tomcat)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值