自定义spring boot stater

今天尝试写了个自定义spring boot starter, 做下笔记。

介绍

spring boot可以简化项目对spring繁琐的配置,遵循约定大于配置的原则。在没有spring boot之前, 应用里面要引入spring data jpa的时候, 需要每个应用都需要引入jpa依赖包,hibernate依赖包,以及jdbc依赖包。在使用spirng boot的时候, 只需要引入spring-boot-starter-data-jpa就可以。

官方常用的spring boot starter

官方的spring boot starter的命名规制是spring-boot-starter-***

开发中常用的spring boot starters

spring-boot-starter-web,spring-boot-starter-data-jpa,spring-boot-starter-aop

自定义starter

可以编写自定义的spring boot starter, 自定义的spring boot starter命名规则是****-spring-boot-starter

编写自定义spring starter步骤

1. 创建spring boot starter项目

2. 定义AutoConfiguration

3. 配置spring.factories

4.使用方通过maven坐标引用自定义的spring boot starter.

DEMO代码

1. 项目中引入spring boot, 项目继承自spring-boot-starters, 自定一starter依赖spring-boot-starter。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starters</artifactId>
    <version>1.5.11.RELEASE</version>
</parent>
<dependencies>
    <!-- 自定义starter依赖此spring-boot-starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
</dependencies>

2. 编写业务代码

public class MyTester {

    public String hello(String name) {
        return "hello " + name;
    }

}

3. 编写auto-configuration代码

auto-configuration是通过@Configuration类实现的,auto-configuration classes 使用@ConditionalOnClass and @ConditionalOnMissingBean注解。

@Configuration
public class MyAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public MyTester getMyTester() {
        MyTester myTester = new MyTester();
        return myTester;
    }

}

4. 编写spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.zxrao.MyAutoConfiguration

参考文档

spring boot官方文档

44. Creating your own auto-configuration

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值