SuperAPI AI Directory

springboot-microservice-gen

General & other

View repository

Updated 10-16 08:49

About this skill

SpringBoot-Microservice-Gen One-click generation of a Spring Boot microservice project skeleton (cross-platform)

Applicable scenarios

Use this Skill when the user wants to generate a fully featured Spring Boot backend skeleton in the current workspace. The generated project includes:

  • Spring CLI Install/verify (spring command, from spring-attic/spring-cli)
  • spring initializr new Generate a Maven + Web basic project
  • RESTful CRUD: Complete CRUD APIs for the User entity (/api/users)+ Paged query(/api/users/page)
  • MyBatis-Plus + MySQL: Data access layer + pagination plugin configuration
  • Redis: Spring Cache caching (@Cacheable/@CacheEvict) + JSON serialization configuration
  • Nacos Config Center:bootstrap.yml + @RefreshScope Dynamic refresh example (configuration uses Nacos)
  • Nacos service discovery (Discovery):/api/discovery/services List registered services and instances
  • OpenFeign remote calls:/api/feign/users Declarative calls to downstream services, including fallback factory
  • Actuator: Health check /actuator/health + metrics monitoring /actuator/metrics
  • Unit tests: JUnit 5 + Mockito (WebMvcTest + pure unit tests),mvn test run
  • Docker Compose orchestration: One-click startup of MySQL (including initialization scripts), Redis, Nacos, Prometheus, Grafana, ELK, and SkyWalking
  • Monitoring stack: Prometheus scrapes /actuator/prometheus, Grafana preset data sources, ELK log collection (logstash profile), SkyWalking distributed tracing
  • Start/stop scripts: Cross-platform start.sh / start.cmd(start|stop|restart|status, automatic packaging + background running)
  • Application Dockerization: Multi-stage Dockerfile + docker-build.sh / docker-build.cmd(build|run|compose),docker-compose.yml built-in app One-click build and containerized run of services
  • Unified response wrapper Result<T>, Lombok, parameter validation

⚠️ Note: This Skill uses spring-attic/spring-cli(the new Spring CLI), and the old Spring Boot CLI (spring-boot-cli-*-bin.zip) aretwo different projects. The new Spring CLI uses the spring boot new / spring initializr new command and no longer supports the old spring init, and running the CLI itself requires JDK 17+。

Nacos Config Center uses Spring Cloud Alibaba spring-cloud-starter-alibaba-nacos-config (Spring Boot 3.2+ must use this solution; the old nacos-config-spring-boot-starter only supports up to 3.1.x).

Cross-platform implementation

The core script is implemented in Python,Windows / macOS / Linux compatible, no need for perl/envsubst/find/awk/unzip and other platform-related tools; only the following must be installed locally:

  • JDK 17+(Spring CLI runtime dependency)
  • Python 3(to run this script; on Windows you can use python / py, macOS/Linux usually has it built in)

Script location:

springboot-microservice-gen/scripts/springboot-microservice-gen.py

Recommended approach: run the script directly

Windows(PowerShell / CMD)

python springboot-microservice-gen\scripts\springboot-microservice-gen.py

macOS / Linux

python3 springboot-microservice-gen/scripts/springboot-microservice-gen.py

Specify the project directory name

python springboot-microservice-gen\scripts\springboot-microservice-gen.py my-app

After the script completes, it outputs:

  • Command to enter the directory
  • Startup command (Windows: mvnw.cmd spring-boot:run;Unix: ./mvnw spring-boot:run)
  • Example API address (GET /api/users)

Maven multi-environment configuration (switching among local / dev / test / prod)

The project uses Maven profile + resource filtering to achieve one-click switching among four environments, while supporting local debugging and the Nacos Config Center:

# ① 本地调试(默认,无需 Nacos;使用本地 MySQL/Redis)
mvnw.cmd clean package -Plocal
mvnw.cmd spring-boot:run            # 默认即 local

# ② 接入 Nacos 配置中心(dev / test / prod)
mvnw.cmd clean package -Pdev        # 或 -Ptest / -Pprod
mvnw.cmd spring-boot:run -Pdev
  • pom.xml: Define local(default)/dev/test/prod four profiles, and through maven-resources-plugin resource filtering inject @env@ injection application.yml of spring.profiles.active(delimiter @ to avoid conflict with Spring ${...} conflict)
  • bootstrap.yml: uses bootstrap direct connection to the Nacos config center, automatically pulls environment-specific configuration by active profile (dataId=<服务名>-<env>.yaml)
  • application.yml: Common configuration (port/logging/MyBatis-Plus/Actuator, etc.),does not include datasource/redis(varies by environment, placed in Nacos)
  • application-local.yml: Dedicated for local debugging, configures localhost data source/Redis, and disables Nacos service registration and config pulling (completely detached from Nacos)
  • Configuration such as datasource/redis for each environment (dev/test/prod), uniformly written in separate dataIds in the Nacos console (<服务名>-dev.yaml / -test.yaml / -prod.yaml)
  • ConfigController(@RefreshScopedemo app.greeting configuration dynamic refresh

Resource address reference principles: do not hardcode IPs. For local debugging use localhost(application-local.yml); for Docker deployment use compose service name(mysql/redis/nacos) as the hostname, overridden by injection from docker-compose environment (see below).

What the script does (operational guidance for the Agent)

  1. Check JDK 17+ (required for Spring CLI to run)
  2. Detect whether spring is available; if unavailable, download spring-cli-<version>.zip from GitHub Release and unzip/install it
    • Download address:https://github.com/spring-attic/spring-cli/releases/download/v<version>/spring-cli-<version>.zip
    • Prefer the java -jar method to invoke the fat jar, avoiding shell script platform differences
  3. Run spring initializr new --project maven-project --dependencies web ... to generate the project
    • If the CLI is unavailable or execution fails, fall back to directly calling start.spring.io to download the project archive
  4. Modify pom.xml(pure string replacement, idempotent):
    • properties:java.version / spring-cloud.version / spring-cloud-alibaba.version
    • dependencyManagement:Spring Cloud BOM + Spring Cloud Alibaba BOM
    • dependencies:MyBatis-Plus、MySQL、Redis、Validation、Actuator、Micrometer Prometheus、Logstash Logback Encoder、Nacos Config、Nacos Discovery、OpenFeign、LoadBalancer、Spring Cloud Bootstrap、Spring Boot Test、Lombok
  5. Generate example code and configuration via templates:
    • controller: UserController (CRUD + pagination), ConfigController (Nacos configuration), FeignController (OpenFeign), DiscoveryController (service discovery)
    • service / service.impl:UserService + UserServiceImpl(@Cacheable/@CacheEvict Redis cache + pagination)
    • entity: User (with @NotBlank/@NotNull validation)
    • mapper:UserMapper(BaseMapper)
    • feign: UserFeignClient + UserFeignClientFallbackFactory (OpenFeign declarative invocation and fallback)
    • config: RedisConfig (JSON serialization + @EnableCaching)
    • common: Result unified response wrapper
    • Root package: MybatisPlusConfig (pagination plugin) + Application (@EnableDiscoveryClient / @EnableFeignClients)
    • src/test:UserControllerTest(WebMvcTest)+ UserServiceImplTest(Mockito)
    • resources:bootstrap.yml(Nacos config center bootstrap) + application.yml(common configuration) + application-local.yml(local debugging, localhost) + logback-spring.xml(ELK logging) + README.md
    • Root directory:start.sh / start.cmd(start/stop),Dockerfile + .dockerignore + docker-build.sh / docker-build.cmd(application image build)
    • deploy/:docker-compose.yml(application app, default) + docker-compose.middleware.yml(middleware MySQL/Redis/Nacos) + docker-compose.monitor.yml(monitoring Prometheus/Grafana/ELK/SkyWalking) + mysql/init.sql + Prometheus/Grafana/ELK configuration

Interface list after generation

Interface Method Description
/api/users GET / POST User list / add
/api/users/page?current=1&size=10 GET User pagination query
/api/users/{id} GET / PUT / DELETE Details / update / delete
/api/config GET Nacos configuration example (@RefreshScope dynamic refresh)
/api/discovery/services GET Service discovery: list of registered services
/api/discovery/services/{name} GET Service discovery: specified service instance
/api/feign/users GET OpenFeign remote invocation example
/actuator/health GET Health check
/actuator/metrics GET Metrics monitoring
/actuator/prometheus GET Prometheus metrics (Grafana dashboard data source)

Docker Compose deployment and monitoring

The generated project's deploy/ directory has built-in one-click startup orchestration,the application / middleware / monitoring are divided into three compose files, which can be started and stopped independently:

cd <projectName>/deploy
docker compose up -d                                     # 应用 app(默认 docker-compose.yml)
docker compose -f docker-compose.middleware.yml up -d    # 中间件:MySQL/Redis/Nacos
docker compose -f docker-compose.monitor.yml up -d       # 监控:Prometheus/Grafana/ELK/SkyWalking
File Content
docker-compose.yml Application (app), default file
docker-compose.middleware.yml MySQL、Redis、Nacos
docker-compose.monitor.yml Prometheus、Grafana、Elasticsearch、Logstash、Kibana、SkyWalking OAP/UI
  • MySQL:mysql/init.sql On first startup, automatically creates the database and tables + sample data
  • Redis: local 6379, AOF persistence
  • Nacos: local 8848, config center + registry center
  • Prometheus: scrapes the application /actuator/prometheus
  • Grafana:localhost:3000(admin/admin), with a preconfigured Prometheus data source
  • ELK: Elasticsearch + Logstash + Kibana; after the application enables the logstash profile, logs are sent as JSON to ES
  • SkyWalking:OAP + UI(localhost:80, the default port has been changed from 8080 to 80). The application image has a built-in SkyWalking Java Agent (-javaagent), non-intrusive distributed tracing, reporting to skywalking-oap:11800; the service name/reporting address are configured via the environment variables SW_AGENT_NAME / SW_AGENT_COLLECTOR_BACKEND_SERVICES configured

The three compose files are located in the same deploy/ directory, by default share the same project name, and share the same <project>_default network, so app can directly access mysql/redis/nacosby service name. Recommended startup order: middleware first, then the application.

Optional environment variables

  • SPRING_CLI_VERSION: default 0.9.0(corresponding to spring-attic/spring-cli 's Release version)
  • SPRING_CLI_INSTALL_DIR: default ~/.cache/springboot-microservice-gen
  • SPRING_CLI_ZIP: specify the path of the locally downloaded spring-cli-<version>.zip (used when network access is restricted)
  • SPRING_BOOT_VERSION: the Spring Boot version used by the generated project; if left empty, the start.spring.io official default is used
  • SPRING_CLOUD_VERSION: default 2023.0.1(compatible with Spring Boot 3.2/3.3)
  • SPRING_CLOUD_ALIBABA_VERSION: default 2023.0.1.3(Nacos config center + service discovery)

If the generated Spring Boot version changes, please adjust synchronously the SPRING_CLOUD_VERSION / SPRING_CLOUD_ALIBABA_VERSION。

resource addresses and environment variables (do not hard-code IPs)

The project does not hard-code IPs in the configuration; middleware addresses are injected via environment variables, allowing switching between different deployment forms:

Environment variable Description Local default Docker (service name)
NACOS_SERVER_ADDR(or SPRING_CLOUD_NACOS_SERVER_ADDR) Nacos address 127.0.0.1:8848 nacos:8848
SPRING_DATASOURCE_URL Data source URL jdbc:mysql://localhost:3306/demo jdbc:mysql://mysql:3306/demo
SPRING_DATASOURCE_USERNAME / SPRING_DATASOURCE_PASSWORD Database account root / root root / root
SPRING_DATA_REDIS_HOST / SPRING_DATA_REDIS_PORT Redis address localhost:6379 redis:6379
  • Local debugging:application-local.yml use localhost(MySQL/Redis just need to run on the host machine).
  • Docker deployment:deploy/docker-compose.yml use the compose service name(mysql/redis/nacos) as the hostname injected into environment, within the same <project>_default network DNS resolution, no IP needed.
  • dev/test/prod: datasource/redis etc. are written in the dataId for each environment in Nacos.

Code generator (MyBatis-Plus Generator, generates CRUD by table)

The project has built-in the official MyBatis-Plus code generator, which can generate entity / mapper / service / serviceImpl / controller (including pagination) from database tables with one click; templates are customizable.

  • Place the initialization tool in src/test/java/.../generator/CodeGenerator.java(test scope dependency, not packaged into the runtime jar)
  • The Freemarker templates are located in src/main/resources/templates/generator/*.ftl, aligned with this project's layered style (Result<T>, service interface + impl,/page pagination, Lombok,@Mapper)

Usage steps:

  1. Modify the CodeGenerator in URL/USERNAME/PASSWORD and TABLES table names;
  2. Run main(run directly in the IDE, or mvn test-compile exec:java -Dexec.mainClass=<...>.generator.CodeGenerator);
  3. Java code is generated to src/main/java, XML is generated to src/main/resources/mapper。

Example conversation trigger phrases

  • "Help me install Spring CLI and use spring initializr to generate a project"
  • "Generate a Spring Boot project with CRUD, Redis, MySQL, Nacos, and health checks in the current directory"
  • "Generate a springboot project like a scaffold, with RESTful CRUD, pagination, Redis caching, Nacos configuration and discovery, OpenFeign calls, and unit tests"