文章原文:https://tlanyan.pp.ua/spring-boot-mybatis-freemarker-ehcache-web-development/

之前做的Java我的项目都是接手自他人,本人没有独立开发过。这几天抽空钻研了一下Spring Boot做web开发,本文用作记录和参考应用。

筹备工作

  1. 装置InteliJ IDEA;InteliJ IDEA基本上是Java和安卓开发必备工具,社区版可收费应用;
  2. 装置Mysql或Mariadb数据库。

应用Spring Boot + MyBatis + FreeMarker进行web开发

创立Spring Boot我的项目

1. 关上IDEA,创立新我的项目,在疏导对话框当选“Spring Initializr”,并自定义项目名称、包名,抉择Java SDK和版本等:

2. 抉择Spring Boot DevTools、Lombok、Spring Web、Freemarker、MyBatis和MySQL这几个包:

生成的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.4.5</version>    <relativePath/> <!-- lookup parent from repository --></parent><groupId>com.tlanyan</groupId><artifactId>springboot</artifactId><version>0.0.1-SNAPSHOT</version><name>springboot</name><description>Demo project for Spring Boot</description><properties>    <java.version>1.8</java.version></properties><dependencies>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-freemarker</artifactId>    </dependency>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-web</artifactId>    </dependency>    <dependency>        <groupId>org.mybatis.spring.boot</groupId>        <artifactId>mybatis-spring-boot-starter</artifactId>        <version>2.1.4</version>    </dependency>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-devtools</artifactId>        <scope>runtime</scope>        <optional>true</optional>    </dependency>    <dependency>        <groupId>mysql</groupId>        <artifactId>mysql-connector-java</artifactId>        <scope>runtime</scope>    </dependency>    <dependency>        <groupId>org.projectlombok</groupId>        <artifactId>lombok</artifactId>        <optional>true</optional>    </dependency>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-test</artifactId>        <scope>test</scope>    </dependency></dependencies><build>    <plugins>        <plugin>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-maven-plugin</artifactId>            <configuration>                <excludes>                    <exclude>                        <groupId>org.projectlombok</groupId>                        <artifactId>lombok</artifactId>                    </exclude>                </excludes>            </configuration>        </plugin>    </plugins></build>

</project>

3. 因为没有配置数据库等,我的项目此时还无奈启动。在根目录下创立 application.yml 文件,输出如下内容:

server:
port: 9000

spring:
freemarker:

template-loader-path: classpath:/templatescache: truesuffix: .ftl

datasource:

url: jdbc:mysql://127.0.0.1:3306/demo?characterEncoding=utf-8&useSSL=false&useUnicode=trueusername: rootpassword: passworddriver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
mapper-locations: classpath:/templates/mapper/*Mapper.xml # mapper文件地位
type-aliases-package: com.tlanyan.springboot.entity

如果相熟properties文件的写法,能够间接编辑 src/resources文件夹下的application.properties文件

此时我的项目能够失常运行(Run -> Run "SpringbootApplication")。

Spring Boot托管动态文件

动态资源放到 src/resources/static 目录下即可被拜访到(增加新文件后需从新运行程序):

除了默认创立的static目录,动态资源文件还能够寄存到public、resources和META-INF/resouces目录下。

Spring Boot + MyBatis + Spring MVC + FreeMarker

MyBatis 是一款优良的长久层框架,它反对自定义 SQL、存储过程以及高级映射。MyBatis 罢黜了简直所有的 JDBC 代码以及设置参数和获取后果集的工作。MyBatis 能够通过简略的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,一般老式 Java 对象)为数据库中的记录。

首先创立数据库表对应的实体类:

package com.tlanyan.springboot.entity;

import lombok.Data;

import java.io.Serializable;

@Data
public class User implements Serializable {

private Integer id;private String name;

}

而后创立Mapper接口:

package com.tlanyan.springboot.mapper;

import com.tlanyan.springboot.entity.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface UserMapper {

public User findById(Integer id);public List getAll();

}

以及在templates/mapper目录下创立UserMapper.xml文件(mapper文件需放到配置文件中的指定目录下,templates中的文件会被主动打包,因而咱们抉择这个地位):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tlanyan.springboot.mapper.UserMapper">

<select id="findById" resultType="com.tlanyan.springboot.entity.User">    SELECT * from user WHERE id = #{id}</select><select id="getAll" resultType="com.tlanyan.springboot.entity.User">    select * from user</select>

</mapper>

接下来编写service层:

package com.tlanyan.springboot.service;

import com.tlanyan.springboot.entity.User;

import java.util.List;

public interface UserService {

public User findById(Integer id);public List<User> getAll();

}

以及其实现:

package com.tlanyan.springboot.service.impl;

import com.tlanyan.springboot.entity.User;
import com.tlanyan.springboot.mapper.UserMapper;
import com.tlanyan.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

@Autowiredprivate UserMapper userMapper;@Overridepublic User findById(Integer id) {    return userMapper.findById(id);}@Overridepublic List<User> getAll() {    return userMapper.getAll();}

}

而后controller层:

package com.tlanyan.springboot.controller;

import com.tlanyan.springboot.entity.User;
import com.tlanyan.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class UserController {

@Autowiredprivate UserService userService;@RequestMapping("/user/list")public String List(Model model) {    List<User> users = userService.getAll();    model.addAttribute("users", users);    return "user/index";}@RequestMapping("/user/{id}")public String view(@PathVariable("id") Integer id, Model model) {    User user = userService.findById(id);    model.addAttribute("user", user);    return "user/view";}

}

最初编写Freemarker模板。在 resources/templates 文件夹下创立user文件夹,新建index.ftl输出下列内容:

<h1>User List</h1>

<ul>

<#list users as user>    <li>ID: ${user.id}, name: ${user.name}</li></#list>

</ul>

以及 view.ftl:

<h1>User ID: ${user.id}, name: ${user.name}</h1>

数据库创立user表,并灌入数据,运行程序,程序输入后果如下:

至此,Spring Boot + MyBatis + Spring MVC + Freemarker曾经齐全能失常工作。

Spring Boot应用Ehcache缓存

最初介绍应用Ehcache缓存加强程序性能。

首先引入Ehcache依赖。在pom.xml中引入ehcache:

...<dependency>    <groupId>net.sf.ehcache</groupId>    <artifactId>ehcache</artifactId></dependency>

</dependencies>

而后在resouces目录下创立ehcache.xml配置文件(Spring Boot会扫描这个门路,因而请保障文件名正确),并输出以下内容:

<ehcache>

<diskStore path="java.io.tmpdir"/><defaultCache        maxElementsInMemory="10000"        eternal="false"        timeToIdleSeconds="120"        timeToLiveSeconds="120"        overflowToDisk="false"        diskPersistent="false"        diskExpiryThreadIntervalSeconds="120"/><cache name="user"       maxElementsInMemory="10000"       eternal="true"       overflowToDisk="true"       diskPersistent="true"       diskExpiryThreadIntervalSeconds="600"/>

</ehcache>

其中:

  1. name:缓存名称。
  2. maxElementsInMemory:缓存最大个数。
  3. eternal:对象是否永恒无效,一但设置了,timeout将不起作用。
  4. timeToIdleSeconds:设置对象在生效前的容许闲置工夫(单位:秒)。仅当eternal=false对象不是永恒无效时应用,可选属性,默认值是0,也就是可闲置工夫无穷大。
  5. timeToLiveSeconds:设置对象在生效前容许存活工夫(单位:秒)。最大工夫介于创立工夫和生效工夫之间。仅当eternal=false对象不是永恒无效时应用,默认是0.,也就是对象存活工夫无穷大。
  6. overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
  7. diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有本人的一个缓冲区。
  8. maxElementsOnDisk:硬盘最大缓存个数。
  9. diskPersistent:是否缓存虚拟机重启期数据。
  10. diskExpiryThreadIntervalSeconds:磁盘生效线程运行工夫距离,默认是120秒。
  11. memoryStoreEvictionPolicy:当达到maxElementsInMemory限度时,Ehcache将会依据指定的策略去清理内存。默认策略是LRU(最近起码应用)。你能够设置为FIFO(先进先出)或是LFU(较少应用)。
  12. clearOnFlush:内存数量最大时是否革除。
  13. diskStore 则示意长期缓存的硬盘目录。

而后在应用程序中配置开启缓存:

package com.tlanyan.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class SpringbootApplication {

public static void main(String\[\] args) {    SpringApplication.run(SpringbootApplication.class, args);}

}

以及在service层开启缓存:

package com.tlanyan.springboot.service.impl;

import com.tlanyan.springboot.entity.User;
import com.tlanyan.springboot.mapper.UserMapper;
import com.tlanyan.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@CacheConfig(cacheNames = "user")
public class UserServiceImpl implements UserService {

@Autowiredprivate UserMapper userMapper;@Override@Cacheablepublic User findById(Integer id) {    return userMapper.findById(id);}@Override@Cacheablepublic List<User> getAll() {    return userMapper.getAll();}

}

留神,cacheNames的值须要在ehcache.xml中存在。

参考

  1. Spring Boot干货系列:(一)优雅的入门篇
  2. SpringBoot+MySQL+MyBatis的入门教程
  3. Springboot系列(四)web动态资源配置
  4. Spring Boot 缓存利用 Ehcache 入门教程
  5. Spring Boot2 系列教程(三十)Spring Boot 整合 Ehcache