Convert Figma logo to code with AI

lihengming logospring-boot-api-project-seed

:seedling::rocket:一个基于Spring Boot & MyBatis的种子项目,用于快速构建中小型API、RESTful API项目~

9,565
3,783
9,565
111

Top Related Projects

🚀一个用来深入学习并实战 Spring Boot 的项目。

about learning Spring Boot via examples. Spring Boot 教程、技术栈示例代码,快速简单上手教程。

spring boot 实践学习案例,是 spring boot 初学者及核心技术巩固的最佳实践。

《Spring Boot基础教程》,2.x版本持续连载中!点击下方链接直达教程目录!

基于SpringCloud2.1的微服务开发脚手架,整合了spring-security-oauth2、nacos、feign、sentinel、springcloud-gateway等。服务治理方面引入elasticsearch、skywalking、springboot-admin、zipkin等,让项目开发快速进入业务开发,而不需过多时间花费在架构搭建上。持续更新中

一个涵盖六个专栏:Spring Boot 2.X、Spring Cloud、Spring Cloud Alibaba、Dubbo、分布式消息队列、分布式事务的仓库。希望胖友小手一抖,右上角来个 Star,感恩 1024

Quick Overview

Spring Boot API Project Seed is a starter template for building RESTful APIs using Spring Boot. It provides a basic project structure, common configurations, and utility classes to help developers quickly set up and start developing Spring Boot-based API projects.

Pros

  • Pre-configured project structure with best practices for Spring Boot API development
  • Includes common utilities and configurations, reducing boilerplate code
  • Supports code generation for basic CRUD operations
  • Integrates popular libraries like MyBatis and PageHelper for database operations and pagination

Cons

  • Limited documentation, especially for non-Chinese speakers
  • May include unnecessary dependencies for some projects
  • Lacks extensive customization options out of the box
  • Not actively maintained, with the last update being over a year ago

Code Examples

  1. Using the BaseService for CRUD operations:
@Service
public class UserService extends AbstractService<User> {
    @Autowired
    private UserMapper userMapper;

    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }
}
  1. Implementing a REST controller:
@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping
    public Result add(@RequestBody User user) {
        userService.save(user);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/{id}")
    public Result detail(@PathVariable Integer id) {
        User user = userService.findById(id);
        return ResultGenerator.genSuccessResult(user);
    }
}
  1. Configuring application properties:
spring.profiles.active=dev
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
mybatis.mapper-locations=classpath:mapper/*.xml

Getting Started

  1. Clone the repository:

    git clone https://github.com/lihengming/spring-boot-api-project-seed.git
    
  2. Configure your database connection in src/main/resources/application-dev.properties.

  3. Run the project:

    ./mvnw spring-boot:run
    
  4. Generate code for your entity:

    ./mvnw generate-sources
    
  5. Start developing your API endpoints in the generated controller classes.

Competitor Comparisons

🚀一个用来深入学习并实战 Spring Boot 的项目。

Pros of spring-boot-demo

  • More comprehensive, covering a wider range of Spring Boot features and integrations
  • Better organized with separate modules for different functionalities
  • More actively maintained with frequent updates and contributions

Cons of spring-boot-demo

  • Potentially overwhelming for beginners due to its extensive scope
  • May include unnecessary components for simple projects
  • Requires more setup time to understand and utilize all features

Code Comparison

spring-boot-api-project-seed:

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

spring-boot-demo:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}

The spring-boot-demo implementation provides more detailed CORS configuration, allowing for greater control over cross-origin requests. This exemplifies the project's more comprehensive approach to Spring Boot features and configurations.

about learning Spring Boot via examples. Spring Boot 教程、技术栈示例代码,快速简单上手教程。

Pros of spring-boot-examples

  • Covers a wide range of Spring Boot topics and use cases
  • Includes examples for various Spring Boot integrations (e.g., Redis, MongoDB, RabbitMQ)
  • Regularly updated with new examples and improvements

Cons of spring-boot-examples

  • Less focused on providing a complete project structure
  • May require more effort to adapt examples into a production-ready application
  • Lacks some advanced features like API versioning and Swagger integration

Code Comparison

spring-boot-api-project-seed:

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.company.project.web"))
            .paths(PathSelectors.any())
            .build();
    }
}

spring-boot-examples:

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

The spring-boot-api-project-seed example shows Swagger configuration, which is not present in spring-boot-examples. However, spring-boot-examples focuses on demonstrating various Spring Boot features and integrations across multiple smaller projects.

spring boot 实践学习案例,是 spring boot 初学者及核心技术巩固的最佳实践。

Pros of springboot-learning-example

  • More comprehensive coverage of Spring Boot features and use cases
  • Includes examples for various Spring Boot integrations (e.g., Redis, MongoDB, MyBatis)
  • Better suited for learning and exploring different aspects of Spring Boot

Cons of springboot-learning-example

  • Less focused on providing a ready-to-use project structure
  • May require more effort to extract specific components for use in a production project
  • Lacks some of the production-ready features found in spring-boot-api-project-seed

Code Comparison

spring-boot-api-project-seed:

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

springboot-learning-example:

@Configuration
public class CorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}

Both repositories demonstrate CORS configuration, but spring-boot-api-project-seed uses a more concise approach by extending WebMvcConfigurerAdapter, while springboot-learning-example uses a separate configuration class with a Bean method.

《Spring Boot基础教程》,2.x版本持续连载中!点击下方链接直达教程目录!

Pros of SpringBoot-Learning

  • More comprehensive coverage of Spring Boot topics, including tutorials and examples
  • Regularly updated with new content and examples
  • Larger community engagement and contributions

Cons of SpringBoot-Learning

  • Less focused on providing a ready-to-use project structure
  • May require more time to navigate and find specific information
  • Not specifically tailored for API development

Code Comparison

spring-boot-api-project-seed:

@Configuration
public class MybatisConfigurer {
    @Bean
    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        factory.setTypeAliasesPackage(MODEL_PACKAGE);
        return factory.getObject();
    }
}

SpringBoot-Learning:

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

The code comparison shows that spring-boot-api-project-seed focuses on configuration and setup for a specific use case (Mybatis integration), while SpringBoot-Learning provides more general examples of Spring Boot applications.

基于SpringCloud2.1的微服务开发脚手架,整合了spring-security-oauth2、nacos、feign、sentinel、springcloud-gateway等。服务治理方面引入elasticsearch、skywalking、springboot-admin、zipkin等,让项目开发快速进入业务开发,而不需过多时间花费在架构搭建上。持续更新中

Pros of SpringCloud

  • Comprehensive microservices architecture with service discovery, gateway, and configuration management
  • Implements advanced features like distributed tracing and centralized logging
  • Includes security implementations with OAuth2 and JWT

Cons of SpringCloud

  • More complex setup and steeper learning curve for beginners
  • Potentially overkill for smaller projects or monolithic applications
  • Requires more resources to run due to multiple services

Code Comparison

SpringCloud (OAuth2 configuration):

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/api/**").authenticated()
            .antMatchers("/").permitAll();
    }
}

spring-boot-api-project-seed (Basic security configuration):

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/api/**").authenticated()
            .anyRequest().permitAll();
    }
}

The SpringCloud example showcases a more advanced OAuth2 resource server configuration, while spring-boot-api-project-seed uses a simpler security setup suitable for basic authentication needs.

一个涵盖六个专栏:Spring Boot 2.X、Spring Cloud、Spring Cloud Alibaba、Dubbo、分布式消息队列、分布式事务的仓库。希望胖友小手一抖,右上角来个 Star,感恩 1024

Pros of SpringBoot-Labs

  • More comprehensive coverage of Spring Boot topics and integrations
  • Regularly updated with new examples and features
  • Includes detailed documentation and explanations for each module

Cons of SpringBoot-Labs

  • Larger and more complex project structure, potentially overwhelming for beginners
  • Less focused on providing a ready-to-use project template
  • May require more time to understand and implement specific features

Code Comparison

SpringBoot-Labs example (Spring Security configuration):

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated().and().formLogin();
    }
}

spring-boot-api-project-seed example (MyBatis configuration):

@Configuration
@MapperScan("com.company.project.dao")
public class MybatisConfigurer {
    @Bean
    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        return factory.getObject();
    }
}

Both repositories provide valuable resources for Spring Boot developers, but they serve different purposes. SpringBoot-Labs offers a wide range of examples and integrations, making it an excellent learning resource. spring-boot-api-project-seed, on the other hand, provides a more streamlined template for quickly starting API projects.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Licence GitHub Release

简介

Spring Boot API Project Seed 是一个基于Spring Boot & MyBatis的种子项目,用于快速构建中小型API、RESTful API项目,该种子项目已经有过多个真实项目的实践,稳定、简单、快速,使我们摆脱那些重复劳动,专注于业务代码的编写,减少加班。下面是一个简单的使用演示,看如何基于本项目在短短几十秒钟内实现一套简单的API,并运行提供服务。

请选择超清

特征&提供

  • 最佳实践的项目结构、配置文件、精简的POM(查看项目结构图)
  • 统一响应结果封装及生成工具
  • 统一异常处理
  • 简单的接口签名认证
  • 常用基础方法抽象封装
  • 使用Druid Spring Boot Starter 集成Druid数据库连接池与监控
  • 使用FastJsonHttpMessageConverter,提高JSON序列化速度
  • 集成MyBatis、通用Mapper插件、PageHelper分页插件,实现单表业务零SQL
  • 提供代码生成器根据表名生成对应的Model、Mapper、MapperXML、Service、ServiceImpl、Controller等基础代码,其中Controller模板默认提供POST和RESTful两套,根据需求在CodeGenerator.genController(tableName)方法中自己选择,默认使用POST模板。代码模板可根据实际项目的需求来扩展,由于每个公司业务都不太一样,所以只提供了一些比较基础、通用的模板,**主要是提供一个思路**来减少重复代码的编写,我在实际项目的使用中,其实根据公司业务的抽象编写了大量的模板。另外,使用模板也有助于保持团队代码风格的统一
  • 另有彩蛋,待你探索  

快速开始

  1. 克隆项目
  2. 对test包内的代码生成器CodeGenerator进行配置,主要是JDBC,因为要根据表名来生成代码
  3. 如果只是想根据上面的演示来亲自试试的话可以使用test resources目录下的demo-user.sql,否则忽略该步
  4. 输入表名,运行CodeGenerator.main()方法,生成基础代码(可能需要刷新项目目录才会出来)
  5. 根据业务在基础代码上进行扩展
  6. 对开发环境配置文件application-dev.properties进行配置,启动项目,Have Fun!  

开发建议

  • 表名,建议使用小写,多个单词使用下划线拼接
  • Model内成员变量建议与表字段数量对应,如需扩展成员变量(比如连表查询)建议创建DTO,否则需在扩展的成员变量上加@Transient注解,详情见通用Mapper插件文档说明
  • 建议业务失败直接使用ServiceException("message")抛出,由统一异常处理器来封装业务失败的响应结果,比如throw new ServiceException("该手机号已被注册"),会直接被封装为{"code":400,"message":"该手机号已被注册"}返回,无需自己处理,尽情抛出
  • 需要工具类的话建议先从apache-commons-*和guava中找,实在没有再造轮子或引入类库,尽量精简项目
  • 开发规范建议遵循阿里巴巴Java开发手册(最新版下载)
  • 建议在公司内部使用ShowDoc、SpringFox-Swagger2 、RAP等开源项目来编写、管理API文档  

技术选型&文档

License

无,纯粹开源分享,感谢大家 Star & Fork 的支持。