1. 程式人生 > 實用技巧 >Springboot與scala編寫第一個web程式

Springboot與scala編寫第一個web程式

1、pom.xml檔案

<?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.0.5.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <
groupId>com.demo</groupId> <artifactId>spark</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spark</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version
> <scala.version>2.11.8</scala.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <!--新增Scala依賴--> <dependency> <groupId>org.scala-lang</groupId> <artifactId>scala-library</artifactId> <version>${scala.version}</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <!-- 編譯scala的外掛 --> <plugin> <groupId>net.alchim31.maven</groupId> <artifactId>scala-maven-plugin</artifactId> <version>3.2.2</version> </plugin> <!-- 編譯java的外掛 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>org.scala-tools</groupId> <artifactId>maven-scala-plugin</artifactId> <executions> <execution> <goals> <goal>compile</goal> <goal>testCompile</goal> </goals> </execution> </executions> <configuration> <recompileMode>incremental</recompileMode> <scalaVersion>${scala.version}</scalaVersion> <launchers> <launcher> <id>app</id> <mainClass>com.web.SparkApplication</mainClass> <args> <arg>-deprecation</arg> </args> <jvmArgs> <jvmArg>-Xms256m</jvmArg> <jvmArg>-Xmx2048m</jvmArg> </jvmArgs> </launcher> </launchers> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <executions> <execution> <phase>compile</phase> <goals> <goal>compile</goal> </goals> </execution> </executions> </plugin> <!-- 打jar外掛 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.4.3</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <filters> <filter> <artifact>*:*</artifact> <excludes> <exclude>META-INF/*.SF</exclude> <exclude>META-INF/*.DSA</exclude> <exclude>META-INF/*.RSA</exclude> </excludes> </filter> </filters> </configuration> </execution> </executions> </plugin> </plugins> </build> <profiles> <profile> <id>dev</id> <properties> <activatedProperties>dev</activatedProperties> </properties> <!-- 這裡代表預設使用dev環境配置檔案 --> <activation> <activeByDefault>true</activeByDefault> </activation> </profile> <profile> <id>test</id> <properties> <activatedProperties>test</activatedProperties> </properties> </profile> <profile> <id>prod</id> <properties> <activatedProperties>prod</activatedProperties> </properties> </profile> </profiles> </project>
View Code

2、啟動檔案類,包含兩個

  a)AppConfig.java

package com.web

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter

/**
  * @author yangwj
  * @date 2020/8/7 10:24
  */

@SpringBootApplication(scanBasePackages = Array("com.web.*"))
class AppConfig extends WebMvcConfigurerAdapter {

}

b)SparkApplication.java

package com.web

import org.springframework.boot.SpringApplication

/**
  * @author yangwj
  * @date 2020/8/7 10:25
  */
object SparkApplication  extends App {
  SpringApplication.run(classOf[AppConfig])
}

3、domain層,實體物件,Person.java

package com.web.domain

import javax.persistence.{Entity, GeneratedValue, Id, Table}

import scala.beans.BeanProperty

/**
  * @author yangwj
  * @date 2020/8/7 10:02
  */
@Entity
@Table
class Person {
  @Id
  @GeneratedValue
  @BeanProperty
  var id:Integer = _

  @BeanProperty
  var name:String = _

  @BeanProperty
  var sex:String = _
}
View Code

4、service和serviceImpl層

a) PersonRepository.java

package com.web.service

import com.web.domain.Person
import org.springframework.data.repository.CrudRepository

/**
  * @author yangwj
  * @date 2020/8/7 10:06
  */
trait PersonRepository extends CrudRepository[Person,Integer]{

}

b)PersonServiceImpl.java

package com.web.service.impl

import com.web.domain.Person
import com.web.service.PersonRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

/**
  * @author yangwj
  * @date 2020/8/7 10:07
  */
@Service
class PersonServiceImpl  @Autowired()(personRepository: PersonRepository) {
  /**
    * 儲存
    *
    * @param person 儲存物件
    * @return Person
    */
  @Transactional
  def save(person: Person): Person = {
    personRepository.save(person)
  }

  /**
    * 根據Id查詢
    * @param id 查詢引數
    * @return Person
    */
  def selectPersonById(id: Integer): Person = {
    personRepository.findById(id).get()
  }
}

5、controller層:PersonController.java

package com.web.controller

import com.web.domain.Person
import com.web.service.impl.PersonServiceImpl
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.{GetMapping, PostMapping, RequestBody, RequestMapping, RequestParam, RestController}

/**
  * @author yangwj
  * @date 2020/8/7 10:09
  */
@RestController
@RequestMapping(Array("/v1/person"))
class PersonController @Autowired()(personService: PersonServiceImpl) {
  @PostMapping
  def save(@RequestBody person: Person): Person = {
    personService.save(person)
  }

  @GetMapping
  def selectPersonById(@RequestParam id: Integer): Person = {
    personService.selectPersonById(id)
  }
}

6、建立資料庫

/*
Navicat MySQL Data Transfer

Source Server         : 本機
Source Server Version : 50726
Source Host           : localhost:3306
Source Database       : spark

Target Server Type    : MYSQL
Target Server Version : 50726
File Encoding         : 65001

Date: 2020-08-07 10:58:25
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for person
-- ----------------------------
DROP TABLE IF EXISTS `person`;
CREATE TABLE `person` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(12) DEFAULT NULL,
  `sex` varchar(2) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of person
-- ----------------------------
INSERT INTO `person` VALUES ('1', '1', '1');
View Code

7、執行:http://localhost:7777/v1/person?id=1

如有不懂,可留言