Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use kotlin to integrate springboot Development

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is about how to use kotlin to integrate springboot development. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

First, install support plug-ins

Install the kotlin plug-in in idea (in most cases it will be installed by default)

II. Attention to maven configuration

Kotlin currently does not support lombok, so you cannot use or reference lombok-related plug-ins or dependency packages. Here is an example of exclusion, and maven-enforcer-plugin is not supported.

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

Property configuration of 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

Necessary dependence

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

Compiling part

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 Java-test-compile test-compile testCompile Org.apache.maven.plugins maven-assembly-plugin 2.6 make-assembly package single ${main.class} jar-with-dependencies

If there is a mixture of java and kotlin, add the following compilation plug-in under the above

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

This maven configuration integrates the compilation of querydsl, mapstruct and dagger2, and can basically meet the needs of general use.

Third, create entry function class

Fourth, write entry function

The starting method of springboot and the configuration of swagger

EnableAsync@EnableSwagger2@EnableScheduling@SpringBootApplicationclass KotlinDemoApplication: CommandLineRunner {companion object {@ JvmStatic fun main (args: Array) {SpringApplication.run (KotlinDemoApplication::class.java) * args)} @ Bean fun api (): Docket {return Docket (DocumentationType.SWAGGER_2) .preferredParameterTypes (Session::class.java) .select () / .apis (RequestHandlerSelectors.any ()) .apis (RequestHandlerSelectors.basePackage ("com.ayouran.flow.controllers")) .upload (PathSelectors.any ()) .build () .apiInfo (ApiInfoBuilder () .description ("ayouram-flow related API") .title ("ayouram-flow") .version ("1.0") .build ()) .pathMapping ("/")} override fun run (vararg args: String?) {println ("* * ok *")} 5. Create database object import com.fasterxml.jackson.annotation.JsonFormatimport org.hibernate.annotations.DynamicInsertimport org.hibernate.annotations.DynamicUpdateimport java.util.*import javax.persistence.*/**** * device traffic rules * / @ 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@DynamicInsertclass DeviceRules {@ Id @ Column (name = "id", columnDefinition = "bigint (20) COMMENT'ID, self-increment'") @ GeneratedValue (strategy = GenerationType.IDENTITY) var id: Long? = null @ Column (name = "device_no", columnDefinition = "varchar (18) COMMENT 'device number'") var deviceNo: String? = null @ Column (name = "rules_no") ColumnDefinition = "varchar (18) COMMENT 'Rule number'") var rulesNo: String? = null @ JsonFormat (pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @ Column (name = "create_at", columnDefinition = "datetime COMMENT 'creation time'") var createAt: Date? = null @ Column (name = "update_at" ColumnDefinition = "datetime COMMENT 'modification time'") var updateAt: Date? = null / * Logic to trigger jpa update code * / @ PreUpdate fun preUpdate () {updateAt = Date ()} / * automatically sets the value of the necessary fields * / @ PrePersist fun prePersist () {updateAt = Date () CreateAt = updateAt deleted = BaseEnum.NOT_REMOVE.index}}

The annotation uses the function of hibernate to automatically create / update table structure and index generation. If you need the mybatis version, you just need to remove the comments.

6. Create warehouse operation interface

Repository based on springboot-data-jpa

@ Repositoryinterface DeviceRulesRepository: JpaRepository, JpaSpecificationExecutor, QuerydslPredicateExecutor {fun getAllByDeviceNoAndDeleted (deviceNo: String, deleted: Int): Optional} 7. Create a business interface to declare the business interface DeviceService {/ * query device routing rules * / fun queryDeviceFlowRules (aPageRequest: APageRequest): PageResult} 8, create a business interface implementation to implement the declared business @ Serviceclass DeviceServiceImpl @ Autowiredconstructor (privateval deviceRepository: DeviceRepository, privateval deviceRulesRepository: DeviceRulesRepository) Privateval querydslUtlis: QuerydslUtlis, privateval deviceMapstruct: DeviceMapstruct): DeviceService {privateval 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.pageIndexpositions!-1) * aPageRequest.pageSizeframes!) .limit (aPageRequest.pageSizeframes!) .fetchResults () return PageUtlis.retPage (results) QuerydslUtlis.getCollection (results.results, exprs, QueryDeviceFlowRulesVO::class.java) as Collection)}

Querydsl is used here to complete a multi-table query

9. Create a http service interface @ RestWrapper@RestController@RequestMapping ("/ device") @ Api (value = "device", description = "device-related interface", tags = ["device"]) class DeviceController @ Autowiredconstructor (privateval deviceService: DeviceService) {@ GetMapping ("/ query_device") fun queryDevice (aPageRequest: APageRequest) = deviceService.queryDevice (aPageRequest) @ GetMapping ("/ query_device_flow_rules") fun queryDeviceFlowRules (aPageRequest: APageRequest) = deviceService.queryDeviceFlowRules (aPageRequest)}

At this point, you can complete a basic development process. In most cases, you can paste the java code directly into the kotlin file, which will be automatically converted into the appropriate kotlin code (occasionally need to adjust yourself, after all, the editor is not omnipotent).

Thank you for reading! This is the end of this article on "how to use kotlin to integrate springboot development". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report