SpringBoot(一)快速入门

经过一段时间的研究和使用,暂时并不考虑花太多时间去学这个东西,为了工作蛮弄吧……

常规的项目框架,使用SpringBoot可以轻松搭建起来,因为大部分的事情SpringBoot都帮我们做了;

但是想写点东西放到SpringBoot中,困难程度比Spring要高不少。

就像在Spring中使用Mybatis,Mybatis是一个独立的框架,脱离Spring也可以用,如果想集成到Spring中,需要添加Spring-Mybatis的jar包;

封装代码已经很麻烦了,如果想在SpringBoot中添加自己写的东西,还要再写一份适配代码,那是真的烦;

开发下来,确实能感觉到Xml配置在解耦方面要优于注解,“零配置”的想法很好,但是,这跟代码解耦,和降低开发难度相悖的。

(当然,你也可以在SpringBoot中启用Xml配置就是了……)

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开发,能用主函数启动也很正常。

此时往static目录下放置静态资源文件,启动项目就可以直接访问,不需要做任何配置。

SpringBootApplication:SpringBoot主函数
ComponentScan:扫描包配置
MapperScan:Mybatis扫描包配置(配置了MapperScan,ylm文件就可以不配置,@Mapper注解不使用也正常运行)

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文件即可(代码在后面给出)

持久层配置

使用的是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>

猜你喜欢

转载自www.cnblogs.com/chenss15060100790/p/9094977.html