自定义一个 starter

自定义一个 starter

1、什么是 starter

Starter是Spring Boot项目中的一个重要概念,它是一种方便开发者快速集成和配置常用功能模块的依赖包。Starter实质上是一个Maven项目,它打包了一组相关的依赖和默认配置,以便于在Spring Boot应用中快速引入和使用。

Spring Boot提供了大量的官方Starter,例如spring-boot-starter-web、spring-boot-starter-data-jpa、spring-boot-starter-security等,还有第三方或社区提供的各种Starter。这些Starter使得在Spring Boot项目中引入和集成常用功能模块变得非常便捷,开发者可以快速搭建起一个功能完善的应用。

本文将通过一个简单案例,可以自定义一个属于自己的 starter

2、写一个功能类

1、建一个模块,名叫 ip-counter-boot-sterter

在这里插入图片描述

2、写 service 层,先写接口,再写实现类

package service;

public interface IpCounterService {
    void record();
}

// 实现类就是根据ip统计访问次数
package service.impl;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import service.IpCounterService;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class IpCounterServiceImpl implements IpCounterService {
    @Autowired
    private HttpServletRequest request;
    private Map<String,Integer> map = new HashMap<>();
    

    @Override
    public void record() {
        String ip = request.getRemoteAddr();
        Integer i = map.get(ip);
        i = Objects.isNull(i) ? 1 : i + 1;
        map.put(ip,i);
        map.forEach((key,val) -> {
            System.out.println("ip : " + key + "\t count : " + val);
        });
    }
}

3、写自动配置类

也很简单,就是写一个能返回功能类的配置类

package config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import service.IpCounterService;
import service.impl.IpCounterServiceImpl;
@Configuration
public class IpAutoConfiguration {
    @Bean
    public IpCounterService ipCounterService() {
        return new IpCounterServiceImpl();
    }
}

4、把自动配置类引入到 Spring 环境中(重要)

步骤也很简单,就是在 resources 目录下创建文件夹

META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports(注意 spring3 之后是这个,之前是 spring.factories,这个在2.7被废止)文件里面的内容是我们写的配置类的全路径,接着就可以在我们需要使用的模块添加依赖,再通过依赖注入的方式进行使用。

在这里插入图片描述

文件中的内容就是自动配置类的全路径名

在这里插入图片描述

5、在 maven 中安装,并添加依赖到测试模块

在这里插入图片描述

创建一个测试模块,就是需要引入 starter 包的模块:

在这里插入图片描述

然后 dependencies 里面进行引入:

在这里插入图片描述

6、在测试模块进行测试

package com.example.testIpCounter.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import service.IpCounterService;

@RestController
public class IndexController {
    @Autowired
    private IpCounterService ipCounterService;

    @GetMapping("/starter")
    public String index() {
        ipCounterService.record();
        return "hello,starter !!!!!!";
    }

    @RequestMapping("/aaa")
    public String aaa() {
        return "aaa";
    }
}

在这里插入图片描述

测试结果:

http://127.0.0.1:8082/starter

在这里插入图片描述

7、写一个拦截器功能,让它更像 starter

package interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import service.IpCounterService;

public class IpCounterInterceptor implements HandlerInterceptor {
    @Autowired
    private IpCounterService ipCounterService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        ipCounterService.record();
        return true;
    }
}


package config;

import interceptor.IpCounterInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(interceptor()).addPathPatterns("/**");
    }

    @Bean
    public IpCounterInterceptor interceptor() {
        return new IpCounterInterceptor();
    }
}


重新 clean & install ,测试模块就算不显示调用 record 方法,也会有监控 ip 的功能。

<think>嗯,用户想要通过网站生成一个Spring Boot Demo项目,并且自定义一个Starter然后打包使用。首先,我需要确认用户的需求。他们可能对Spring Boot有一定的基础了解,但可能不清楚如何创建自定义Starter。需要分步骤指导,确保每个环节都清晰。 首先,创建Spring Boot项目。用户可能知道Spring Initializr,但需要详细步骤,比如访问哪个网址,选择哪些依赖。这里要提醒他们选择Web或者必要的依赖,不过对于Starter来说可能不需要,但生成项目结构是基础。 接下来,自定义Starter部分。需要解释Starter的结构,包括autoconfigure和starter模块的区别。用户可能混淆这两个部分,所以需要明确说明。然后,创建配置类、自动配置类,以及如何让Spring识别这些配置。这里要提到@Configuration和@EnableConfigurationProperties,确保用户正确使用注解。 然后是properties文件的配置,比如添加提示信息,这样在application.properties里输入时会有自动提示。这部分用户可能不熟悉,需要详细说明如何创建spring-configuration-metadata.json文件。 打包和安装部分,用户可能需要使用Maven命令,所以要给出具体的mvn install命令,并说明如何查看是否成功安装到本地仓库。这里要确保用户了解Maven仓库的结构,以及groupId、artifactId、version的作用。 最后,在Demo项目中使用自定义Starter,需要添加依赖,并演示如何通过属性配置和使用服务类。用户可能会遇到找不到Bean的情况,所以提醒他们检查自动配置是否正确,或者是否添加了@Enable注解。 可能用户在实际操作中会遇到问题,比如自动配置未生效,这时候需要常见问题排查,比如检查spring.factories的位置,或者是否引入了starter依赖。这部分需要提前预见到,并在步骤中给出提示。 需要确保所有代码示例正确,特别是LaTeX格式的行内公式,但在这个问题中可能用不上,不过要遵循系统指令,检查是否有数学表达式需要转换。当前问题不涉及数学公式,所以可能不需要,但要注意其他指令,比如使用中文,结构清晰等。 总结下来,步骤分为创建项目、构建Starter模块、自动配置、打包、使用和问题排查。确保每个步骤都有明确的代码示例和说明,避免用户遗漏关键配置。同时,使用简单的语言,避免专业术语过多,让新手也能理解。</think>我将分步骤为您演示如何创建Spring Boot项目并自定义Starter: 一、创建Spring Boot基础项目 1. 访问 https://start.spring.io 2. 选择: - Project: Maven - Language: Java - Spring Boot: 推荐3.x版本 3. 添加依赖:暂时不需要特殊依赖 4. 点击"GENERATE"下载项目 二、构建自定义Starter模块 1. 在项目中新建子模块: ```shell my-spring-boot-project/ ├── my-starter-autoconfigure/ # 核心实现 ├── my-starter/ # 空壳依赖 └── demo/ # 测试项目 ``` 2. 核心配置(my-starter-autoconfigure) ```java // MyServiceProperties.java @ConfigurationProperties(prefix = "my.service") public class MyServiceProperties { private String prefix = "[DEFAULT]"; private String suffix = "!"; // 省略getter/setter } // MyServiceAutoConfiguration.java @Configuration @EnableConfigurationProperties(MyServiceProperties.class) @ConditionalOnClass(MyService.class) public class MyServiceAutoConfiguration { @Bean @ConditionalOnMissingBean public MyService myService(MyServiceProperties properties) { return new MyService(properties.getPrefix(), properties.getSuffix()); } } // MyService.java public class MyService { private final String prefix; private final String suffix; public MyService(String prefix, String suffix) { this.prefix = prefix; this.suffix = suffix; } public String wrap(String content) { return prefix + content + suffix; } } ``` 3. 创建spring.factories文件 ```properties # src/main/resources/META-INF/spring.factories org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.example.autoconfigure.MyServiceAutoConfiguration ``` 4. 添加配置提示(可选) ```json # src/main/resources/META-INF/spring-configuration-metadata.json { "properties": [ { "name": "my.service.prefix", "type": "java.lang.String", "defaultValue": "[DEFAULT]" }, { "name": "my.service.suffix", "type": "java.lang.String", "defaultValue": "!" } ] } ``` 三、打包安装 ```shell # 在my-starter-autoconfigure目录下执行 mvn clean install # 验证安装(注意替换版本号) ls ~/.m2/repository/com/example/my-starter-autoconfigure/1.0.0/ ``` 四、使用自定义Starter 1. 在demo模块中添加依赖: ```xml <dependency> <groupId>com.example</groupId> <artifactId>my-starter-autoconfigure</artifactId> <version>1.0.0</version> </dependency> ``` 2. 配置application.properties: ```properties my.service.prefix=Hello my.service.suffix=! ``` 3. 使用示例: ```java @RestController public class DemoController { private final MyService myService; public DemoController(MyService myService) { this.myService = myService; } @GetMapping("/test") public String test() { return myService.wrap("World"); } } ``` 常见问题排查: 1. 自动配置不生效时检查: - 确认spring.factories文件路径正确 - 检查是否包含@Conditional注解条件 - 确保starter依赖已正确引入 2. 配置提示不显示时: - 检查spring-configuration-metadata.json格式 - 确认文件位于META-INF目录 通过以上步骤即可完成自定义Starter的开发和使用。实际项目中可根据需求添加更多条件判断、指标监控等功能模块。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值