您好,登錄后才能下訂單哦!
Scala是一門多范式的編程語言,一種類似Java的編程語言,設(shè)計(jì)初衷是實(shí)現(xiàn)可伸縮的語言并集成面向?qū)ο缶幊獭cala把Erlang風(fēng)格的基于actor的并發(fā)帶進(jìn)了JVM,開發(fā)者可以利用Scala的actor模型在JVM上設(shè)計(jì)具伸縮性的并發(fā)應(yīng)用程序,它會(huì)自動(dòng)獲得多核心處理器帶來的優(yōu)勢,而不必依照復(fù)雜的Java線程模型來編寫程序,接下來就介紹一下如何在SpringBoot框架中使用Scala來進(jìn)行簡單的Web開發(fā),對(duì)scala不了解的建議先去學(xué)習(xí)基礎(chǔ)哦
一、導(dǎo)入依賴
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.gjing.project</groupId> <artifactId>scala-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>scala-demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.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-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!--加入Scala依賴庫--> <dependency> <groupId>org.scala-lang</groupId> <artifactId>scala-library</artifactId> <version>2.13.1</version> </dependency> <dependency> <groupId>cn.gjing</groupId> <artifactId>tools-starter-swagger</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>cn.gjing</groupId> <artifactId>tools-common</artifactId> <version>1.2.7</version> </dependency> </dependencies> <build> <plugins> <!--加入Scala的編譯插件,否則無法進(jìn)行編譯--> <plugin> <groupId>org.scala-tools</groupId> <artifactId>maven-scala-plugin</artifactId> <version>2.15.2</version> <executions> <execution> <goals> <goal>compile</goal> <goal>testCompile</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
通過上面我們可以發(fā)現(xiàn),和創(chuàng)建Java版本的SpringBoot項(xiàng)目沒啥不同,只是引入了scala-library這個(gè)我們之前沒引入的包,同時(shí)增加了對(duì)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 # 設(shè)置創(chuàng)表引擎為Innodb,不然默認(rèn)為MyiSam database-platform: org.hibernate.dialect.MySQL5InnoDBDialect swagger: base-package: com.gjing.project.scala.controller title: scala學(xué)習(xí)的demo
三、創(chuàng)建實(shí)體類
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開發(fā)沒啥不同,只是@BeanProperty注解會(huì)幫我們生成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不同的是泛型采用的是[]中括號(hào),這點(diǎn)要注意
五、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 分頁對(duì)象 * @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("用戶的相關(guān)功能")) 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 = "頁數(shù)",required = true,dataType = "int",paramType = "query"), new ApiImplicitParam(name = "size",value = "條數(shù)",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("刪除成功") } }
這樣我們一個(gè)簡單的Scala版本的Web項(xiàng)目就寫好啦,只需要啟動(dòng)就可以試著運(yùn)行啦,本文的源代碼地址:scala-demo,有任何不清楚的可以在評(píng)論區(qū)回復(fù)哈
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。