使用kotlin集成springboot开发代码实例

作者:袖梨 2022-06-29

本篇文章小编给大家分享一下使用kotlin集成springboot开发代码实例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

目前大多数都在使用java集成springboot进行开发,本文演示仅仅将java换成kotlin,其他不变的情况下进行开发。

一、安装支持插件

在idea中安装kotlin插件(大多数情况下会默认安装了)

二、maven配置 注意

kotlin目前不支持lombok所以不能使用或引用lombok相关的插件或依赖包,下面是一个排除示例,同时也不支持maven-enforcer-plugin


            com.ayouran.common
            a-common
            1.0.0-SNAPSHOT
            
                 
                       org.projectlombok
                       lombok
                 
            

maven的属性配置


        UTF-8
        UTF-8
        1.8
        1.8
        1.8
        1.3.21
        
        true
        
        enable
        2.2.4.RELEASE
        Hoxton.SR1
        2.7.0
        com.lc.github.KotlinDemoApplication
        4.2.1
        1.3.1.Final
    

必要的依赖


       
        
            org.jetbrains.kotlin
            kotlin-reflect
            ${kotlin.version}
        
     
        
            org.jetbrains.kotlin
            kotlin-stdlib-jdk8
            ${kotlin.version}
        
    

编译部分

 
        
            
                org.jetbrains.kotlin
                kotlin-maven-plugin
                
                    true
                    ${kotlin.language.version}
                
                
                    
                        org.jetbrains.kotlin
                        kotlin-maven-allopen
                        ${kotlin.version}
                    
                
                
                    
                        kapt
                        
                            kapt
                        
                        
                            true
                            
                                src/main/kotlin
                                src/main/java
                            
                            
                                
                                    com.google.dagger
                                    dagger-compiler
                                    2.9
                                
                                
                                    com.querydsl
                                    querydsl-apt
                                    ${querydsl.version}
                                    jpa
                                
                                
                                    org.mapstruct
                                    mapstruct-processor
                                    ${mapstruct.version}
                                
                            
                        
                    
                    
                        compile
                        
                            compile
                        
                        
                            
                                src/main/kotlin
                                src/main/java
                            
                        
                    
                    
                        test-kapt
                        
                            test-kapt
                        
                        
                            
                                src/test/kotlin
                                src/test/java
                            
                            
                                
                                    com.google.dagger
                                    dagger-compiler
                                    2.9
                                
                                
                                    com.querydsl
                                    querydsl-apt
                                    ${querydsl.version}
                                    jpa
                                
                                
                                    org.mapstruct
                                    mapstruct-processor
                                    ${mapstruct.version}
                                
                            
                        
                    
                    
                        test-compile
                        
                            test-compile
                        
                        
                            
                                src/test/kotlin
                                src/test/java
                                target/generated-sources/kapt/test
                            
                        
                    
                
            
            
                org.apache.maven.plugins
                maven-compiler-plugin
                3.8.1
                
                    none
                    ${java.version}
                    ${java.version}
                    
                        
                            org.projectlombok
                            lombok
                            ${lombok.version}
                        
                        
                            org.mapstruct
                            mapstruct-processor
                            ${mapstruct.version}
                        
                    
                    
                        -Amapstruct.suppressGeneratorTimestamp=true
                        -Amapstruct.defaultComponentModel=spring
                    
                
                
                    
                    
                        default-compile
                        none
                    
                    
                    
                        default-testCompile
                        none
                    
                    
                        java-compile
                        compile
                        
                            compile
                        
                    
                    
                        java-test-compile
                        test-compile
                        
                            testCompile
                        
                    
                
            
            
                org.apache.maven.plugins
                maven-assembly-plugin
                2.6
                
                    
                        make-assembly
                        package
                        
                            single
                        
                        
                            
                                
                                    ${main.class}
                                
                            
                            
                                jar-with-dependencies
                            
                        
                    
                
            
        
    

有java与kotlin混合的情况,在上面的下加入下面的编译插件


                            org.apache.maven.plugins
                            maven-compiler-plugin
                            3.8.1
                            
                                none
                                ${java.version}
                                ${java.version}
                                
                                    
                                        org.mapstruct
                                        mapstruct-processor
                                        ${mapstruct.version}
                                    
                                
                                
                                    -Amapstruct.suppressGeneratorTimestamp=true
                                    -Amapstruct.defaultComponentModel=spring
                                
                            
                            
                                
                                
                                    default-compile
                                    none
                                
                                
                                
                                    default-testCompile
                                    none
                                
                                
                                    java-compile
                                    compile
                                    
                                        compile
                                    
                                
                                
                                    java-test-compile
                                    test-compile
                                    
                                        testCompile
                                    
                                
                            
                        

此maven配置集成了querydsl、mapstruct、dagger2的编译,基本上能满足常规的使用

三、类

四、编写入口函数

springboot的启动方法及swagger的配置

@EnableAsync
@EnableSwagger2
@EnableScheduling
@SpringBootApplication
class KotlinDemoApplication : CommandLineRunner {
    companion object {
        @JvmStatic
        fun main(args: Array) {
            SpringApplication.run(KotlinDemoApplication::class.java, *args)
        }
    }

    @Bean
    fun api(): Docket {
        return Docket(DocumentationType.SWAGGER_2)
                .ignoredParameterTypes(Session::class.java)
                .select()
//                .apis(RequestHandlerSelectors.any())
                .apis(RequestHandlerSelectors.basePackage("com.ayouran.flow.controllers"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(ApiInfoBuilder()
                        .description("ayouram-flow相关API")
                        .title("ayouram-flow")
                        .version("1.0")
                        .build())
                .pathMapping("/")
    }

    override fun run(vararg args: String?) {
        println("*************************** ok ***********************************")
    }
}

五、创建数据库对象

import com.fasterxml.jackson.annotation.JsonFormat
import org.hibernate.annotations.DynamicInsert
import org.hibernate.annotations.DynamicUpdate
import java.util.*
import javax.persistence.*

/****
 * 设备流量规则
 */
@Entity
@Table(name = "device_rules",
        indexes = [Index(name = "device_no", columnList = "device_no"),
            Index(name = "rules_no", columnList = "rules_no"),
            Index(name = "deleted", columnList = "deleted")],
        uniqueConstraints = [UniqueConstraint(name = "device_no_rules_no", columnNames = ["device_no", "rules_no"])])
@DynamicUpdate
@DynamicInsert
class DeviceRules {

    @Id
    @Column(name = "id", columnDefinition = "bigint(20) COMMENT 'ID,自增'")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long? = null

    @Column(name = "device_no", columnDefinition = "varchar(18) COMMENT '设备编号'")
    var deviceNo: String? = null

    @Column(name = "rules_no", columnDefinition = "varchar(18) COMMENT '规则编号'")
    var rulesNo: String? = null

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @Column(name = "create_at", columnDefinition = "datetime COMMENT '创建时间'")
    var createAt: Date? = null

    @Column(name = "update_at", columnDefinition = "datetime COMMENT '修改时间'")
    var updateAt: Date? = null

    /**
     * 触发jpa update代码需要执行的逻辑
     */
    @PreUpdate
    fun preUpdate() {
        updateAt = Date()
    }

    /**
     * 自动设置必要字段的值
     */
    @PrePersist
    fun prePersist() {
        updateAt = Date()
        createAt = updateAt
        deleted = BaseEnum.NOT_REMOVE.index
    }
}

注解使用了hibernate的功能主要用于自动创建/更新表结构以及索引的生成,如果需要mybatis版本的,只需要去掉这里面的注释就好。

六、创建仓库操作接口

基于springboot-data-jpa的repository

@Repository
interface DeviceRulesRepository : JpaRepository,
        JpaSpecificationExecutor, QuerydslPredicateExecutor {
    fun getAllByDeviceNoAndDeleted(deviceNo: String, deleted: Int): Optional>
}

七、创建一个业务接口来声明业务

interface DeviceService {
  
    /**
     * 查询设备的路由规则
     */
    fun queryDeviceFlowRules(aPageRequest: APageRequest): PageResult
}

八、创建一个业务接口实现来实现声明的业务

@Service
class DeviceServiceImpl @Autowired
constructor(private val deviceRepository: DeviceRepository,
            private val deviceRulesRepository: DeviceRulesRepository,
            private val querydslUtlis: QuerydslUtlis,
            private val deviceMapstruct: DeviceMapstruct) : DeviceService {
    private val logger = LoggerFactory.getLogger(javaClass)
    
    override fun queryDeviceFlowRules(aPageRequest: APageRequest): PageResult {
        val qDeviceRules = QDeviceRules.deviceRules
        val qFlowRules = QFlowRules.flowRules
        var rredicate: Predicate? = null
        if (StringUtils.isNotBlank(aPageRequest.query)) rredicate = qDeviceRules.deviceNo.eq(aPageRequest.query)
        val exprs = arrayOf>(qDeviceRules.deviceNo, qDeviceRules.deleted, qFlowRules.rulesNo, qFlowRules.flowMax,
                qFlowRules.startTime, qFlowRules.endTime)
        val results = querydslUtlis.getQueryFactory()
                .select(*exprs)
                .from(qDeviceRules)
                .where(ExpressionUtils.allOf(rredicate))
                .leftJoin(qFlowRules)
                .on(qDeviceRules.rulesNo.eq(qFlowRules.rulesNo))
                .orderBy(qDeviceRules.createAt.desc())
                .offset((aPageRequest.pageIndex!! - 1) * aPageRequest.pageSize!!)
                .limit(aPageRequest.pageSize!!)
                .fetchResults()
        return PageUtlis.retPage(results, querydslUtlis.getCollection(results.results, exprs, QueryDeviceFlowRulesVO::class.java) as Collection)
    }
}

这里使用了querydsl来完成一个多表查询

九、创建一个 http服务接口

@RestWrapper
@RestController
@RequestMapping("/device")
@Api(value = "device", description = "设备相关接口", tags = ["device"])
class DeviceController @Autowired
constructor(private val deviceService: DeviceService) {

    @GetMapping("/query_device")
    fun queryDevice(aPageRequest: APageRequest) = deviceService.queryDevice(aPageRequest)

    @GetMapping("/query_device_flow_rules")
    fun queryDeviceFlowRules(aPageRequest: APageRequest) = deviceService.queryDeviceFlowRules(aPageRequest)
}

至此完成一个基本的开发过程,大多数情况下可以直接将java代码粘贴到kotlin文件中,会自动转换成合适的kotlin代码(偶尔需要自己调整,毕竟编辑器不是万能的)

相关文章

精彩推荐