SpringBoot3 + Kotlin + mybatis-plus + Swagger3后端开发样例

本文介绍了Kotlin,一种在JVM上运行的静态类型编程语言,重点讲述了其简洁性、静态类型、空安全和扩展函数等特性。文章还强调了Kotlin在Android开发、后端服务(如与SpringBoot集成)和安全性的优势,以及其在Springdoc和Swagger中的应用。
摘要由CSDN通过智能技术生成

前言:

Kotlin 是一种在 JVM(Java 虚拟机)、Android 和浏览器端运行的静态类型编程语言。以下是关于 Kotlin 的总结介绍:
1、语言特性:
简洁性:Kotlin 旨在提供简洁且安全的代码,同时保持与 Java 的互操作性。
静态类型:Kotlin 支持静态类型,这有助于编译器在编译时捕获错误。
空安全:Kotlin 具有强大的空安全特性,可以避免许多常见的空指针异常。
扩展函数:允许为现有类添加新功能,而无需修改原始代码。
2、主要优势:
安全性:Kotlin 提供了一系列特性来增强代码的安全性,如空安全性和智能转换。
互操作性:Kotlin 与 Java 高度兼容,使得在现有 Java 项目中集成 Kotlin 变得容易。
简洁高效:Kotlin 代码通常更简洁,且执行效率高。
现代特性:支持函数式编程特性,如 lambda 表达式和高阶函数。
3、应用领域:
Android 开发:Kotlin 是 Android 开发的首选语言,许多新项目和库都采用 Kotlin 作为主要编程语言。
后端开发:Kotlin 可以与 Spring 等框架无缝集成,用于构建后端服务。
服务器端开发:适用于各种服务器端应用,包括使用 JVM 的应用。
前端开发:虽然主要用于后端和 Android,但 Kotlin/JS 版本也支持前端开发。
4、社区支持:
Kotlin 拥有活跃的社区和大量的学习资源,包括官方文档、教程和开源项目。
许多大型项目已经开始使用 Kotlin,如 Square 的 Retrofit 和 OkHttp。
5、发展趋势:
随着 Kotlin 的不断发展和完善,它在各种应用场景中的使用越来越广泛。
Kotlin 的空安全性和简洁性吸引了越来越多的开发者

一、引包

  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.0</version>
    </parent>


    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>
        <springfox.swagger3.version>3.0.0</springfox.swagger3.version>
        <kotlin.version>1.8.21</kotlin.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3.2</version>
        </dependency>

        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
            <version>2.2.0</version>
        </dependency>

        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-starter-webmvc-api</artifactId>
            <version>2.2.0</version>
        </dependency>

        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
            <version>4.4.0</version>
        </dependency>

        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-stdlib-jdk8</artifactId>
            <version>${kotlin.version}</version>
        </dependency>

        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-test</artifactId>
            <version>${kotlin.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <descriptors>
                        <descriptor>assembly.xml</descriptor>
                    </descriptors>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                           <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.jetbrains.kotlin</groupId>
                <artifactId>kotlin-maven-plugin</artifactId>
                <version>${kotlin.version}</version>
                <executions>
                    <execution>
                        <id>compile</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>test-compile</id>
                        <phase>test-compile</phase>
                        <goals>
                            <goal>test-compile</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <jvmTarget>${maven.compiler.target}</jvmTarget>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <executions>
                    <execution>
                        <id>compile</id>
                        <phase>compile</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>testCompile</id>
                        <phase>test-compile</phase>
                        <goals>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

二、bean

import com.baomidou.mybatisplus.annotation.*
import java.io.Serializable
import java.math.BigDecimal

/**
 * @author zc
 * @date 2024/2/23 10:26
 * @desc
 */
@TableName("test_price")
class PriceBean: Serializable {

    @TableId(type = IdType.ASSIGN_UUID)
    var id: String? = null

    @TableField(value = "price")
    var price: BigDecimal? = null

    @Version
    var version: Int? = null
}

三、mapper

import com.baomidou.mybatisplus.core.mapper.BaseMapper
import com.zc.bean.PriceBean
import org.apache.ibatis.annotations.Mapper

@Mapper
interface TestKotlinMapper: BaseMapper<PriceBean> {
}

四、service

import com.baomidou.mybatisplus.extension.service.IService
import com.zc.bean.PriceBean
import org.springframework.stereotype.Repository

@Repository
interface TestKotlinService: IService<PriceBean> {
}

五、Impl

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.zc.bean.PriceBean
import com.zc.mapper.TestKotlinMapper
import org.springframework.stereotype.Service

/**
 * @author zc
 * @date 2024/4/18 9:56
 * @desc
 */
@Service
open class TestKotlinServcieImpl: ServiceImpl<TestKotlinMapper, PriceBean>(), TestKotlinService{

}

六、controller

说明: swagger3 的实现请参考:SpringBoot3 集成Springdoc 实现Swagger3功能-CSDN博客

import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.zc.bean.PriceBean
import com.zc.service.TestKotlinService
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.Parameter
import io.swagger.v3.oas.annotations.tags.Tag
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController

/**
 * @author zc
 * @date 2024/4/18 10:38
 * @desc
 */
@RestController
@RequestMapping("/price")
@Tag(name = "kotlin")
class TestKotlinController {

    @Autowired
    private lateinit var testKotlinService: TestKotlinService;

    @GetMapping("list")
    @Operation(summary = "list", description = "获取集合")
    fun getPriceBean(@RequestParam(name = "pageNum") @Parameter(name = "pageNum", description = "页数") pageNum: Long = 1,
                     @RequestParam(name = "pageSize") @Parameter(name = "pageSize", description = "每页数") pageSize: Long = 10 ): List<PriceBean>{
        val page = Page<PriceBean>(pageNum, pageSize)
        return testKotlinService.list(page);
    }


    @PostMapping("add")
    @Operation(summary = "add", description = "创建")
    fun addPriceBean(@RequestBody priceBean: PriceBean): String{
        testKotlinService.save(priceBean);
        return "success"
    }

    @DeleteMapping("del/{id}")
    fun deletePriceBean(@PathVariable id: String): String{
        testKotlinService.removeById(id);
        return "success"
    }
}

七、swagger

八、学习文档

API 参考 · Kotlin 官方文档 中文版

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用 Spring Boot 和 Kotlin 更新 API 的详细示例: 1. 创建一个新的 Spring Boot 项目并添加必要的依赖项,如下所示: ```gradle dependencies { implementation("org.springframework.boot:spring-boot-starter-web") implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") implementation("org.jetbrains.kotlin:kotlin-reflect") } ``` 2. 创建一个名为 `User` 的数据类,用于表示要更新的用户: ```kotlin data class User( val id: Long, val name: String, val email: String ) ``` 3. 创建一个名为 `UserController` 的控制器类,用于处理用户更新请求: ```kotlin @RestController @RequestMapping("/api/users") class UserController(private val userRepository: UserRepository) { @PutMapping("/{id}") fun updateUser(@PathVariable id: Long, @RequestBody user: User): User { val existingUser = userRepository.findById(id) .orElseThrow { EntityNotFoundException("User with id $id not found") } existingUser.name = user.name existingUser.email = user.email return userRepository.save(existingUser) } } ``` 4. 创建一个名为 `UserRepository` 的存储库接口,用于访问用户数据: ```kotlin @Repository interface UserRepository : JpaRepository<UserEntity, Long> ``` 5. 创建一个名为 `UserEntity` 的实体类,用于映射到数据库中的用户表: ```kotlin @Entity @Table(name = "users") data class UserEntity( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long = 0, @Column(nullable = false) var name: String, @Column(nullable = false, unique = true) var email: String ) ``` 6. 运行应用程序并使用 cURL 或其他 HTTP 客户端发出更新用户的请求: ```bash curl -X PUT -H "Content-Type: application/json" -d '{"name": "John Doe", "email": "john.doe@example.com"}' http://localhost:8080/api/users/1 ``` 这将更新 ID 为 1 的用户的名称和电子邮件,并返回更新后的用户对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值