微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SpringBoot如何使用Scala进行开发的实现

这篇文章主要介绍了SpringBoot如何使用Scala进行开发的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

Scala是一门多范式的编程语言,一种类似Java的编程语言,设计初衷是实现可伸缩的语言并集成面向对象编程。Scala把Erlang风格的基于actor的并发带进了JVM,开发者可以利用Scala的actor模型在JVM上设计具伸缩性的并发应用程序,它会自动获得多核心处理器带来的优势,而不必依照复杂的Java线程模型来编写程序,接下来就介绍一下如何在SpringBoot框架中使用Scala来进行简单的Web开发,对scala不了解的建议先去学习基础哦

一、导入依赖

4.0.0org.springframework.bootspring-boot-starter-parent2.2.1.RELEASEcom.gjing.projectscala-demo0.0.1-SNAPSHOTscala-demoDemo project for Spring Boot1.8org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-data-jpaMysqLmysql-connector-javaorg.scala-langscala-library2.13.1cn.gjingtools-starter-swagger1.3.0cn.gjingtools-common1.2.7org.scala-toolsmaven-scala-plugin2.15.2compiletestCompileorg.springframework.bootspring-boot-maven-plugin

通过上面我们可以发现,和创建Java版本的SpringBoot项目没啥不同,只是引入了scala-library这个我们之前没引入的包,同时增加了对scala编译的插件

二、配置YML文件

server: port: 8080 spring: application: name: scala-demo datasource: driver-class-name: com.MysqL.cj.jdbc.Driver url: jdbc:MysqL://127.0.0.1:3306/demo?characterEncoding=utf8&useSSL=false username: root password: root type: com.zaxxer.hikari.HikariDataSource hikari: maximum-pool-size: 5 minimum-idle: 1 idle-timeout: 30000 connection-timeout: 30000 jpa: database: MysqL hibernate: ddl-auto: update # 设置创表引擎为Innodb,不然认为MyiSam database-platform: org.hibernate.dialect.MysqL5InnoDBDialect swagger: base-package: com.gjing.project.scala.controller title: scala学习的demo

三、创建实体类

import javax.persistence._ import scala.beans.BeanProperty /** * @author Gjing **/ @Entity @Table(name = "scala_customer") class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @BeanProperty var id:Integer = _ @BeanProperty var customerName:String = _ def this(customerName:String){ this() this.customerName = customerName } override def toString: String = s"Customer($id,$customerName)" }

这块和我们用java开发没啥不同,只是@BeanProperty注解会帮我们生成get和set

四、Repository层

import com.gjing.project.scala.entity.Customer import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository /** * @author Gjing **/ @Repository trait CustomerRepository extends JpaRepository[Customer, Integer] { /** * 通过用户名查询 * @param name 用户名 * @return Customer */ def findByCustomerName(name:String) : Customer }

这里和JAVA不同的是泛型采用的是[]中括号,这点要注意

五、Service层

import cn.gjing.tools.common.result.PageResult import com.gjing.project.scala.entity.Customer import com.gjing.project.scala.exceptions.MyServiceException import com.gjing.project.scala.repository.CustomerRepository import javax.annotation.Resource import org.springframework.data.domain.Pageable import org.springframework.stereotype.Service /** * @author Gjing **/ @Service class CustomerService @Resource()(customerRepository: CustomerRepository) { /** * 保存用户 * * @param name 用户名 */ def saveCustomer(name: String): Unit = { var customer = customerRepository.findByCustomerName(name) if (customer != null) { throw MyServiceException("添加失败,用户已存在") } customer = new Customer(name) customerRepository.save(customer) } /** * 分页查询 * * @param pageable 分页对象 * @return */ def pageCustomer(pageable: Pageable): PageResult[java.util.List[Customer]] = { val page = customerRepository.findAll(pageable) return PageResult.of(page.getContent, page.getTotalPages, page.getSize, page.getTotalElements, page.getNumber) } /** * 更新用户名 * @param id 用户id * @param name 用户名 */ def updateCustomer(id: Integer, name: String): Unit = { val customer = customerRepository.findById(id).orElseThrow(() => MyServiceException("更新失败,用户不存在")) customer.setCustomerName(name) customerRepository.saveAndFlush(customer) } /** * 删除指定用户 * @param id 用户id */ def deleteCustomer(id:Integer): Unit = { val customer = customerRepository.findById(id).orElseThrow(() => MyServiceException("删除失败,用户不存在")) customerRepository.delete(customer) } }

有意思的是,在scala中依赖注入是写在类名上的

六、Controller层

import cn.gjing.tools.common.annotation.NotEmpty import cn.gjing.tools.common.result.PageResult import com.gjing.project.scala.entity.Customer import com.gjing.project.scala.service.CustomerService import io.swagger.annotations.{Api, ApiImplicitParam, ApiImplicitParams, ApiOperation} import javax.annotation.Resource import org.springframework.data.domain.PageRequest import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation._ /** * @author Gjing **/ @RestController @Api(tags = Array("用户的相关功能")) class CustomerController @Resource()(customerService:CustomerService){ @PostMapping(Array("/customer")) @ApiOperation("添加用户") @ApiImplicitParam(name = "customerName",value = "用户名",dataType = "String",required = true,paramType = "query") @NotEmpty def saveCustomer(customerName:String): ResponseEntity[String] ={ customerService.saveCustomer(customerName) ResponseEntity.ok("添加成功") } @GetMapping(Array("/customer_page")) @ApiOperation("分页查询") @ApiImplicitParams(Array( new ApiImplicitParam(name = "page",value = "页数",required = true,dataType = "int",paramType = "query"), new ApiImplicitParam(name = "size",value = "条数",required = true,dataType = "int",paramType = "query"), )) def pageCustomer(page:Integer,size:Integer): ResponseEntity[PageResult[java.util.List[Customer]]]={ ResponseEntity.ok(customerService.pageCustomer(PageRequest.of(page, size))) } @NotEmpty @PutMapping(Array("/customer")) @ApiOperation("更新用户") @ApiImplicitParams(Array( new ApiImplicitParam(name = "id",value = "用户ID",required = true,dataType = "int",paramType = "query"), new ApiImplicitParam(name = "name",value = "用户名",required = true,dataType = "String",paramType = "query") )) def updateCustomer(id:Integer,name:String): ResponseEntity[String] = { customerService.updateCustomer(id, name) ResponseEntity.ok("修改成功") } @DeleteMapping(Array("/customer/{id}")) @ApiOperation("删除用户") def deleteCustomer(id:Integer): ResponseEntity[String] = { customerService.deleteCustomer(id) ResponseEntity.ok("删除成功") } }

这样我们一个简单的Scala版本的Web项目就写好啦,只需要启动就可以试着运行啦,本文的源代码地址:scala-demo,有任何不清楚的可以在评论回复

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐