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、application.yml和application.properties文件

a) application.yml

server:
  port: 7777
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver  #数据库驱动
    url: jdbc:mysql://localhost:3306/spark?useUnicode=true&characterEncoding=utf8&useSSL=false&allowMultiQueries=true&serverTimezone=GMT%2B8 #本地数据库url,先在本地数据库中建立test这个库
    username: root  #数据库用户名
    password: yang156122  #数据库密码

  jpa:
    hibernate:
      ddl-auto: update  #每次运行程序,没有表格会新建表格,表内有数据不会清空,只会更新
    database: mysql

b) application.properties

###对象变量出现大写,自动转为_
spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy

7、创建数据库

/*
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

8、运行:http://localhost:7777/v1/person?id=1

如有不懂,可留言

 

posted @ 2020-08-07 11:00  小白啊小白,Fighting  阅读(487)  评论(0编辑  收藏  举报