栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

自定义spring boot stater

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

自定义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。


    org.springframework.boot
    spring-boot-starters
    1.5.11.RELEASE

    
    
        org.springframework.boot
        spring-boot-starter
    

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/937062.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号