经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Scala » 查看文章
SpringBoot整合Scala构建Web服务的方法
来源:jb51  时间:2019/3/5 8:42:03  对本文有异议

今天我们尝试Spring Boot整合Scala,并决定建立一个非常简单的Spring Boot微服务,使用Scala作为编程语言进行编码构建。

创建项目

初始化项目

复制代码 代码如下:
mvn archetype:generate -DgroupId=com.edurt.ssi -DartifactId=springboot-scala-integration -DarchetypeArtifactId=maven-archetype-quickstart -Dversion=1.0.0 -DinteractiveMode=false

修改pom.xml增加java和scala的支持

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.  
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.edurt.ssi</groupId>
  6. <artifactId>springboot-scala-integration</artifactId>
  7. <packaging>jar</packaging>
  8. <version>1.0.0</version>
  9.  
  10. <name>springboot-scala-integration</name>
  11. <description>SpringBoot Scala Integration is a open source springboot, scala integration example.</description>
  12.  
  13. <parent>
  14. <groupId>org.springframework.boot</groupId>
  15. <artifactId>spring-boot-starter-parent</artifactId>
  16. <version>2.1.3.RELEASE</version>
  17. <relativePath/> <!-- lookup parent from repository -->
  18. </parent>
  19.  
  20. <properties>
  21. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  22. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  23. <java.version>1.8</java.version>
  24. <maven.compiler.source>1.8</maven.compiler.source>
  25. <maven.compiler.target>1.8</maven.compiler.target>
  26. <!-- dependency config -->
  27. <dependency.scala.version>2.12.1</dependency.scala.version>
  28. <!-- plugin config -->
  29. <plugin.maven.scala.version>3.1.3</plugin.maven.scala.version>
  30. </properties>
  31.  
  32. <dependencies>
  33. <dependency>
  34. <groupId>org.scala-lang</groupId>
  35. <artifactId>scala-library</artifactId>
  36. <version>${dependency.scala.version}</version>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.springframework.boot</groupId>
  40. <artifactId>spring-boot-starter-web</artifactId>
  41. </dependency>
  42. </dependencies>
  43.  
  44. <build>
  45. <sourceDirectory>${project.basedir}/src/main/scala</sourceDirectory>
  46. <testSourceDirectory>${project.basedir}/src/test/scala</testSourceDirectory>
  47. <plugins>
  48. <plugin>
  49. <groupId>net.alchim31.maven</groupId>
  50. <artifactId>scala-maven-plugin</artifactId>
  51. <version>${plugin.maven.scala.version}</version>
  52. <executions>
  53. <execution>
  54. <goals>
  55. <goal>compile</goal>
  56. <goal>testCompile</goal>
  57. </goals>
  58. </execution>
  59. </executions>
  60. </plugin>
  61. <plugin>
  62. <groupId>org.springframework.boot</groupId>
  63. <artifactId>spring-boot-maven-plugin</artifactId>
  64. </plugin>
  65. </plugins>
  66. </build>
  67.  
  68. </project>

一个简单的应用类

  1. package com.edurt.ssi
  2.  
  3. import org.springframework.boot.SpringApplication
  4. import org.springframework.boot.autoconfigure.SpringBootApplication
  5.  
  6. @SpringBootApplication
  7. class SpringBootScalaIntegration
  8.  
  9. object SpringBootScalaIntegration extends App{
  10.  
  11. SpringApplication.run(classOf[SpringBootScalaIntegration])
  12.  
  13. }

添加Rest API接口功能

创建一个HelloController Rest API接口,我们只提供一个简单的get请求获取hello,scala输出信息

  1. package com.edurt.ssi.controller
  2.  
  3. import org.springframework.web.bind.annotation.{GetMapping, RestController}
  4.  
  5. @RestController
  6. class HelloController {
  7.  
  8. @GetMapping(value = Array("hello"))
  9. def hello(): String = {
  10. return "hello,scala"
  11. }
  12.  
  13. }
  14.  

修改SpringBootScalaIntegration文件增加以下设置扫描路径

  1. @ComponentScan(value = Array(
  2. "com.edurt.ssi.controller"
  3. ))

添加页面功能

修改pom.xml文件增加以下页面依赖

  1. <!-- mustache -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-mustache</artifactId>
  5. </dependency>

修改SpringBootScalaIntegration文件增加以下设置扫描路径ComponentScan的value字段中

  1. "com.edurt.ssi.view"

在src/main/resources路径下创建templates文件夹

在templates文件夹下创建一个名为hello.mustache的页面文件

  1. <h1>Hello, Scala</h1>

创建页面转换器HelloView

  1. package com.edurt.ssi.view
  2.  
  3. import org.springframework.stereotype.Controller
  4. import org.springframework.web.bind.annotation.GetMapping
  5.  
  6. @Controller
  7. class HelloView {
  8.  
  9. @GetMapping(value = Array("hello_view"))
  10. def helloView: String = {
  11. return "hello";
  12. }
  13.  
  14. }
  15.  

浏览器访问http://localhost:8080/hello_view即可看到页面内容

添加数据持久化功能

修改pom.xml文件增加以下依赖(由于测试功能我们使用h2内存数据库)

  1. <!-- data jpa and db -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-jpa</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.h2database</groupId>
  8. <artifactId>h2</artifactId>
  9. <scope>runtime</scope>
  10. </dependency>

修改SpringBootScalaIntegration文件增加以下设置扫描model路径

  1. @EntityScan(value = Array(
  2. "com.edurt.ssi.model"
  3. ))

创建User实体

  1. package com.edurt.ssi.model
  2.  
  3. import javax.persistence.{Entity, GeneratedValue, Id}
  4.  
  5. @Entity
  6. class UserModel {
  7.  
  8. @Id
  9. @GeneratedValue
  10. var id: Long = 0
  11.  
  12. var name: String = null
  13.  
  14. }

创建UserSupport dao数据库操作工具类

  1. package com.edurt.ssi.support
  2.  
  3. import com.edurt.ssi.model.UserModel
  4. import org.springframework.data.repository.PagingAndSortingRepository
  5.  
  6. trait UserSupport extends PagingAndSortingRepository[UserModel, Long] {
  7.  
  8. }
  9.  

创建UserService服务类

  1. package com.edurt.ssi.service
  2.  
  3. import com.edurt.ssi.model.UserModel
  4.  
  5. trait UserService {
  6.  
  7. /**
  8. * save model to db
  9. */
  10. def save(model: UserModel): UserModel;
  11.  
  12. }
  13.  

创建UserServiceImpl实现类

  1. package com.edurt.ssi.service
  2.  
  3. import com.edurt.ssi.model.UserModel
  4. import com.edurt.ssi.support.UserSupport
  5. import org.springframework.beans.factory.annotation.Autowired
  6. import org.springframework.stereotype.Service
  7.  
  8. @Service(value = "userService")
  9. class UserServiceImpl @Autowired() (
  10. val userSupport: UserSupport
  11. ) extends UserService {
  12.  
  13. /**
  14. * save model to db
  15. */
  16. override def save(model: UserModel): UserModel = {
  17. return this.userSupport.save(model)
  18. }
  19.  
  20. }
  21.  

创建用户UserController进行持久化数据

  1. package com.edurt.ssi.controller
  2.  
  3. import com.edurt.ssi.model.UserModel
  4. import com.edurt.ssi.service.UserService
  5. import org.springframework.beans.factory.annotation.Autowired
  6. import org.springframework.web.bind.annotation.{PathVariable, PostMapping, RequestMapping, RestController}
  7.  
  8. @RestController
  9. @RequestMapping(value = Array("user"))
  10. class UserController @Autowired()(
  11. val userService: UserService
  12. ) {
  13.  
  14. @PostMapping(value = Array("save/{name}"))
  15. def save(@PathVariable name: String): Long = {
  16. val userModel = {
  17. new UserModel()
  18. }
  19. userModel.name = name
  20. return this.userService.save(userModel).id
  21. }
  22.  
  23. }

使用控制台窗口执行以下命令保存数据

  1. curl -X POST http://localhost:8080/user/save/qianmoQ

收到返回结果

1

表示数据保存成功

增加数据读取渲染功能

修改UserService增加以下代码

  1. /**
  2. * get all model
  3. */
  4. def getAll(page: Pageable): Page[UserModel]

修改UserServiceImpl增加以下代码

  1. /**
  2. * get all model
  3. */
  4. override def getAll(page: Pageable): Page[UserModel] = {
  5. return this.userSupport.findAll(page)
  6. }

修改UserController增加以下代码

  1. @GetMapping(value = Array("list"))
  2. def get(): Page[UserModel] = this.userService.getAll(PageRequest.of(0, 10))

创建UserView文件渲染User数据

  1. package com.edurt.ssi.view
  2.  
  3. import com.edurt.ssi.service.UserService
  4. import org.springframework.beans.factory.annotation.Autowired
  5. import org.springframework.data.domain.PageRequest
  6. import org.springframework.stereotype.Controller
  7. import org.springframework.ui.Model
  8. import org.springframework.web.bind.annotation.GetMapping
  9.  
  10. @Controller
  11. class UserView @Autowired()(
  12. private val userService: UserService
  13. ) {
  14.  
  15. @GetMapping(value = Array("user_view"))
  16. def helloView(model: Model): String = {
  17. model.addAttribute("users", this.userService.getAll(PageRequest.of(0, 10)))
  18. return "user"
  19. }
  20.  
  21. }

创建user.mustache文件渲染数据(自行解析返回数据即可)

  1. {{users}}

浏览器访问http://localhost:8080/user_view即可看到页面内容

增加单元功能

修改pom.xml文件增加以下依赖

  1. <!-- test -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-test</artifactId>
  5. <scope>test</scope>
  6. <exclusions>
  7. <exclusion>
  8. <groupId>junit</groupId>
  9. <artifactId>junit</artifactId>
  10. </exclusion>
  11. <exclusion>
  12. <groupId>org.mockito</groupId>
  13. <artifactId>mockito-core</artifactId>
  14. </exclusion>
  15. </exclusions>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.junit.jupiter</groupId>
  19. <artifactId>junit-jupiter-engine</artifactId>
  20. <scope>test</scope>
  21. </dependency>

创建UserServiceTest文件进行测试UserService功能

  1. package com.edurt.ssi
  2.  
  3. import com.edurt.ssi.service.UserService
  4. import org.junit.jupiter.api.Test
  5. import org.springframework.beans.factory.annotation.Autowired
  6. import org.springframework.boot.test.context.SpringBootTest
  7. import org.springframework.data.domain.PageRequest
  8.  
  9. @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
  10. class UserServiceTest @Autowired()(
  11. private val userService: UserService) {
  12.  
  13. @Test
  14. def `get all`() {
  15. println(">> Assert blog page title, content and status code")
  16. val entity = this.userService.getAll(PageRequest.of(0, 1))
  17. print(entity.getTotalPages)
  18. }
  19.  
  20. }
  21.  

源码地址:GitHub

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号