這幾天研究了一下Spring Boot做web開發,本文用作記錄和參考使用,
準備作業
安裝InteliJ IDEA;InteliJ IDEA基本上是Java和安卓開發必備工具,社區版可免費使用;
安裝Mysql或Mariadb資料庫,
使用Spring Boot + MyBatis + FreeMarker進行web開發
創建Spring Boot專案
- 打開IDEA,創建新專案,在引導對話框中選“Spring Initializr”,并自定義專案名稱、包名,選擇Java SDK和版本等:
InteliJ IDEA創建Spring Boot專案

InteliJ IDEA創建Spring Boot專案
- 選擇Spring Boot DevTools、Lombok、Spring Web、Freemarker、MyBatis和MySQL這幾個包:
Spring Boot勾選依賴軟體包

生成的 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>
- 因為沒有配置資料庫等,專案此時還無法啟動,在根目錄下創建 application.yml 檔案,輸入如下內容:
server:
port: 9000
spring:
freemarker:
template-loader-path: classpath:/templates
cache: true
suffix: .ftl
datasource:
url: jdbc:mysql://127.0.0.1:3306/demo?characterEncoding=utf-8&useSSL=false&useUnicode=true
username: root
password: password
driver-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 {
@Autowired
private UserMapper userMapper;
@Override
public User findById(Integer id) {
return userMapper.findById(id);
}
@Override
public 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 {
@Autowired
private UserService userService;
@RequestMapping("/user/list")
public String List(Model model) {
List<User> users = userService.getAll();
model.addAttribute(users);
return "user/index";
}
@RequestMapping("/user/{id}")
public String view(@PathVariable("id") Integer id, Model model) {
User user = userService.findById(id);
model.addAttribute(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 MVC運行結果1
Spring MVC運行結果2

至此,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 {
@Autowired
private UserMapper userMapper;
@Override
@Cacheable
public User findById(Integer id) {
return userMapper.findById(id);
}
@Override
@Cacheable
public List<User> getAll() {
return userMapper.getAll();
}
}
需要注意, cacheNames 的值需要在 ehcache.xml 中存在,
碼字不易,如果覺得本篇文章對你有用的話,請給我一鍵三連!關注作者,后續會有更多的干貨分享,請持續關注!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/278068.html
標籤:java
上一篇:pandas(3):索引Index/MultiIndex
下一篇:Servlet開發
