SpringBoot(一)快速入門

暫時並不考慮花太多時間去學這個東西,爲了工做蠻弄吧……javascript

常規的項目框架,使用SpringBoot能夠輕鬆搭建起來,由於大部分的事情SpringBoot都幫咱們作了;html

可是想寫點東西放到SpringBoot中,困難程度比Spring要高很多。java

 

就像在Spring中使用Mybatis,Mybatis是一個獨立的框架,脫離Spring也能夠用,若是想集成到Spring中,須要添加Spring-Mybatis的jar包;mysql

封裝代碼已經很麻煩了,若是想在SpringBoot中添加本身寫的東西,還要再寫一份適配代碼,那是真的煩。jquery

(固然,你也能夠在SpringBoot中啓用Xml配置就是了……)git

 

SpringBoot目錄

 

main
--java:Java代碼存放目錄
--resources:文件資源存放目錄
    |--static:靜態資源存放目錄(JS、CSS、Html,不作任何配置便可訪問)
    |--templates:頁面模版(動態頁面,通常存放須要渲染的頁面,Freemaker、Beetl、Thymeleaf、Velocity等)
    |--mapping:Mybatis關係映射配置(根據實際需求,可任意指定位置)
--webapp:

pom.xml:Maven配置

test:代碼單元測試

SpringBoot程序入口

確實不可思議,一個Web項目能夠用主函數啓動,不過看了Tomcat的程序目錄,大概也明白怎麼回事:Tomcat不少代碼都是由java開發,能用主函數啓動也很正常。github

項目建立好以後,直接往static目錄下放置靜態資源文件,啓動項目就能夠直接訪問,不須要作任何配置。web

 

SpringBootApplication:SpringBoot主函數
ComponentScan:掃描包配置
MapperScan:Mybatis掃描包配置(配置了MapperScan,ylm文件就能夠不配置,@Mapper註解不使用也正常運行)spring

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * 主函數
 *
 * Created by CSS on 2018/4/28.
 */
@SpringBootApplication
@MapperScan("com.sea.dao")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

模版引擎配置

templates目錄主要用於存放動態頁面,SpringBoot推薦使用thymeleaf,不過我用的性能更好的是FreeMarker,添加maven依賴、配置yml文件便可(代碼在後面給出)sql

持久層配置

使用的是MyBatis,參數是Sql查詢語句,由於是測試,怎麼簡單怎麼來吧。

import org.apache.ibatis.annotations.Mapper;

import java.util.List;
import java.util.Map;

@Mapper
public interface Debug {
    public List<Map<String, Object>> select(String sql) throws Exception;
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sea.dao.Debug">
    <select id="select" parameterType="String" resultType="java.util.HashMap">
        ${value}
    </select>
</mapper>

Controller層

控制層可使用SpringMVC原先的全部註解,且功能同樣;

不要使用RequestMapping("/**")控制全部的動態頁面,會跟靜態資源文件衝突,使用(/**.ftl)便可。

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.dao.Debug;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * Controller
 *
 * Created by CSS on 2018/4/28.
 */
@Controller
public class Core {
    @RequestMapping("/page/**")
    public void core() {
    }

    @Autowired
    Debug mapper;

    @ResponseBody
    @RequestMapping("/data")
    public PageInfo<Map<String, Object>> data() {
        try {
            PageHelper.startPage(1, 2);
            List<Map<String, Object>> list = mapper.select("SELECT * FROM `sys_user`");
            return new PageInfo<Map<String, Object>>(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

單元測試

import com.sea.Application;
import com.sea.dao.Debug;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class PageTest {
    @Autowired
    Debug mapper;

    @Test
    public void testHome() throws Exception {
        System.out.println(mapper.select("SELECT * FROM `sys_user`"));
    }
}

Maven配置

比較特別的就PageHelper(Mybatis分頁插件)和阿里的Druid(鏈接池)了,若是不用刪除便可。

模版引擎看我的喜愛了,JSP我已經一年不用了,沒特別狀況,從此不會再用了吧。

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.sea</groupId>
  <artifactId>SeaBoot</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>SeaBoot Maven Webapp</name>
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/>
  </parent>

  <dependencies>
    <!--單元測試-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <!--數據庫鏈接-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.35</version>
    </dependency>

    <!--Web-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--模版引擎-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-freemarker</artifactId>
    </dependency>
    <!--單元測試-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <!--數據庫-->
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.3.0</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid-spring-boot-starter</artifactId>
      <version>1.1.0</version>
    </dependency>
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper-spring-boot-starter</artifactId>
      <version>1.1.2</version>
    </dependency>
  </dependencies>

  <!--build是IDEA自動生成的-->
  <build>
    <finalName>SeaBoot</finalName>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

Application.yml配置

server:
  port: 8080

spring:
    datasource:
        name: test
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://127.0.0.1:3306/med?useUnicode=true&amp;characterEncoding=utf8&amp;allowMultiQueries=true&amp;autoReconnect=true&amp;failOverReadOnly=false
        username: root
        password: root
        type: com.alibaba.druid.pool.DruidDataSource

        initialSize: 5
        minIdle: 5
        maxActive: 10
        maxWait: 60000
        filters: stat
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20

    #模版引擎
    freemarker:
        template-loader-path: classpath:/templates
        suffix: .ftl
        expose-request-attributes: true
        request-context-attribute: request

#持久層框架
mybatis:
    mapper-locations: classpath:mapping/*.xml

#分頁工具
pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql

測試頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <script type="text/javascript" src="jquery-1.3.2.min.js"></script>
    <title>Title</title>
</head>
<body>
<button id="btn">click</button>
Test Static Html
<script type="text/javascript">
    $(document).ready(function () {
        $("#btn").click(function () {
            alert("-----------------")
        });
    });
</script>
</body>
</html>
相關文章
相關標籤/搜索