基于SpringBoot與Mybatis實現(xiàn)SpringMVC Web項目
一、熱身
一個現(xiàn)實的場景是:當(dāng)我們開發(fā)一個Web工程時,架構(gòu)師和開發(fā)工程師可能更關(guān)心項目技術(shù)結(jié)構(gòu)上的設(shè)計。而幾乎所有結(jié)構(gòu)良好的軟件(項目)都使用了分層設(shè)計。分層設(shè)計是將項目按技術(shù)職能分為幾個內(nèi)聚的部分,從而將技術(shù)或接口的實現(xiàn)細節(jié)隱藏起來。

從另一個角度上來看,結(jié)構(gòu)上的分層往往也能促進了技術(shù)人員的分工,可以使開發(fā)人員更專注于某一層業(yè)務(wù)與功能的實現(xiàn),比如前端工程師只關(guān)心頁面的展示與交互效果(例如專注于HTML,JS等),而后端工程師只關(guān)心數(shù)據(jù)和業(yè)務(wù)邏輯的處理(專注于Java,Mysql等)。兩者之間通過標準接口(協(xié)議)進行溝通。
在實現(xiàn)分層的過程中我們會使用一些框架,例如SpringMVC。但利用框架帶來了一些使用方面的問題。我們經(jīng)常要做的工作就是配置各種XML文件,然后還需要搭建配置Tomcat或者Jetty作為容器來運行這個工程。每次構(gòu)建一個新項目,都要經(jīng)歷這個流程。更為不幸的是有時候前端人員為了能在本地調(diào)試或測試程序,也需要先配置這些環(huán)境,或者需要后端人員先實現(xiàn)一些服務(wù)功能。這就和剛才提到的“良好的分層結(jié)構(gòu)”相沖突。
每一種技術(shù)和框架都有一定的學(xué)習(xí)曲線。開發(fā)人員需要了解具體細節(jié),才知道如何把項目整合成一個完整的解決方案。事實上,一個整合良好的項目框架不僅僅能實現(xiàn)技術(shù)、業(yè)務(wù)的分離,還應(yīng)該關(guān)注并滿足開發(fā)人員的“隔離”。
為了解決此類問題,便產(chǎn)生了Spring Boot這一全新框架。Spring Boot就是用來簡化Spring應(yīng)用的搭建以及開發(fā)過程。該框架致力于實現(xiàn)免XML配置,提供便捷,獨立的運行環(huán)境,實現(xiàn)“一鍵運行”滿足快速應(yīng)用開發(fā)的需求。
與此同時,一個完整的Web應(yīng)用難免少不了數(shù)據(jù)庫的支持。利用JDBC的API需要編寫復(fù)雜重復(fù)且冗余的代碼。而使用O/RM(例如Hibernate)工具需要基于一些假設(shè)和規(guī)則,例如最普遍的一個假設(shè)就是數(shù)據(jù)庫被恰當(dāng)?shù)囊?guī)范了。這些規(guī)范在現(xiàn)實項目中并非能完美實現(xiàn)。由此,誕生了一種混合型解決方案——Mybatis。Mybatis是一個持久層框架,它從各種數(shù)據(jù)庫訪問工具中汲取大量優(yōu)秀的思想,適用于任何大小和用途的數(shù)據(jù)庫。根據(jù)官方文檔的描述:MyBatis 是支持定制化 SQL、存儲過程以及高級映射的優(yōu)秀的持久層框架。MyBatis 避免了幾乎所有的 JDBC 代碼和手動設(shè)置參數(shù)以及獲取結(jié)果集。MyBatis 可以對配置和原生Map使用簡單的 XML 或注解,將接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java對象)映射成數(shù)據(jù)庫中的記錄。
最后,再回到技術(shù)結(jié)構(gòu)分層上,目前主流倡導(dǎo)的設(shè)計模式為MVC,即模型(model)-視圖(view)-控制器(controller)。實現(xiàn)該設(shè)計模式的框架有很多,例如Struts。而前文提到的SpringMVC是另一個更為優(yōu)秀,靈活易用的MVC框架。 SpringMVC是一種基于Java的以請求為驅(qū)動類型的輕量級Web框架,其目的是將Web層進行解耦,即使用“請求-響應(yīng)”模型,從工程結(jié)構(gòu)上實現(xiàn)良好的分層,區(qū)分職責(zé),簡化Web開發(fā)。
目前,對于如何把這些技術(shù)整合起來形成一個完整的解決方案,并沒有相關(guān)的最佳實踐。將Spring Boot和Mybatis兩者整合使用的資料和案例較少。因此,本文提供(介紹)一個完整利用SpringBoot和Mybatis來構(gòu)架Web項目的案例。該案例基于SpringMVC架構(gòu)提供完整且簡潔的實現(xiàn)Demo,便于開發(fā)人員根據(jù)不同需求和業(yè)務(wù)進行拓展。
補充提示,Spring Boot 推薦采用基于 Java 注解的配置方式,而不是傳統(tǒng)的 XML。只需要在主配置 Java 類上添加“@EnableAutoConfiguration”注解就可以啟用自動配置。Spring Boot 的自動配置功能是沒有侵入性的,只是作為一種基本的默認實現(xiàn)。開發(fā)人員可以通過定義其他 bean 來替代自動配置所提供的功能,例如在配置本案例數(shù)據(jù)源(DataSource)時,可以體會到該用法。
二、實踐
一些說明:
項目IDE采用Intellij(主要原因在于Intellij顏值完爆Eclipse,誰叫這是一個看臉的時代)
工程依賴管理采用個人比較熟悉的Maven(事實上SpringBoot與Groovy才是天生一對)
1.預(yù)覽:
(1)github地址
https://github.com/djmpink/springboot-mybatis
git : https://github.com/djmpink/springboot-mybatis.git
(2)完整項目結(jié)構(gòu)
(3)數(shù)據(jù)庫
數(shù)據(jù)庫名:test
【user.sql】
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '7player', '18', '123456');
2.Maven配置
完整的【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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.7player.framework</groupId> <artifactId>springboot-mybatis</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.2.5.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.7</java.version> </properties> <dependencies> <!--Spring Boot--> <!--支持 Web 應(yīng)用開發(fā),包含 Tomcat 和 spring-mvc。 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--模板引擎--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!--支持使用 JDBC 訪問數(shù)據(jù)庫--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--添加適用于生產(chǎn)環(huán)境的功能,如性能指標和監(jiān)測等功能。 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!--Mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <!--Mysql / DataSource--> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!--Json Support--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.43</version> </dependency> <!--Swagger support--> <dependency> <groupId>com.mangofactory</groupId> <artifactId>swagger-springmvc</artifactId> <version>0.9.5</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>spring-milestone</id> <url>https://repo.spring.io/libs-release</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-milestone</id> <url>https://repo.spring.io/libs-release</url> </pluginRepository> </pluginRepositories> </project>
3.主函數(shù)
【Application.java】包含main函數(shù),像普通java程序啟動即可。
此外,該類中還包含和數(shù)據(jù)庫相關(guān)的DataSource,SqlSeesion配置內(nèi)容。
注:@MapperScan(“cn.no7player.mapper”) 表示Mybatis的映射路徑(package路徑)
package cn.no7player;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
@EnableAutoConfiguration
@SpringBootApplication
@ComponentScan
@MapperScan("cn.no7player.mapper")
public class Application {
private static Logger logger = Logger.getLogger(Application.class);
//DataSource配置
@Bean
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource() {
return new org.apache.tomcat.jdbc.pool.DataSource();
}
//提供SqlSeesion
@Bean
public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
/**
* Main Start
*/
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
logger.info("============= SpringBoot Start Success =============");
}
}
4.Controller
請求入口Controller部分提供三種接口樣例:視圖模板,Json,restful風(fēng)格
(1)視圖模板
返回結(jié)果為視圖文件路徑。視圖相關(guān)文件默認放置在路徑 resource/templates下:
package cn.no7player.controller;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HelloController {
private Logger logger = Logger.getLogger(HelloController.class);
/*
* http://localhost:8080/hello?name=cn.7player
*/
@RequestMapping("/hello")
public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
logger.info("hello");
model.addAttribute("name", name);
return "hello";
}
}
(2)Json
返回Json格式數(shù)據(jù),多用于Ajax請求。
package cn.no7player.controller;
import cn.no7player.model.User;
import cn.no7player.service.UserService;
import org.apache.log4j.Logger;
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;
@Controller
public class UserController {
private Logger logger = Logger.getLogger(UserController.class);
@Autowired
private UserService userService;
/*
* http://localhost:8080/getUserInfo
*/
@RequestMapping("/getUserInfo")
@ResponseBody
public User getUserInfo() {
User user = userService.getUserInfo();
if(user!=null){
System.out.println("user.getName():"+user.getName());
logger.info("user.getAge():"+user.getAge());
}
return user;
}
}
(3)restful
REST 指的是一組架構(gòu)約束條件和原則。滿足這些約束條件和原則的應(yīng)用程序或設(shè)計就是 RESTful。
此外,有一款RESTFUL接口的文檔在線自動生成+功能測試功能軟件——Swagger UI,具體配置過程可移步《Spring Boot 利用 Swagger 實現(xiàn)restful測試》
package cn.no7player.controller;
import cn.no7player.model.User;
import com.wordnik.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping(value="/users")
public class SwaggerController {
/*
* http://localhost:8080/swagger/index.html
*/
@ApiOperation(value="Get all users",notes="requires noting")
@RequestMapping(method=RequestMethod.GET)
public List<User> getUsers(){
List<User> list=new ArrayList<User>();
User user=new User();
user.setName("hello");
list.add(user);
User user2=new User();
user.setName("world");
list.add(user2);
return list;
}
@ApiOperation(value="Get user with id",notes="requires the id of user")
@RequestMapping(value="/{name}",method=RequestMethod.GET)
public User getUserById(@PathVariable String name){
User user=new User();
user.setName("hello world");
return user;
}
}
5.Mybatis
配置相關(guān)代碼在Application.java中體現(xiàn)。
(1)【application.properties】
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
注意,在Application.java代碼中,配置DataSource時的注解
@ConfigurationProperties(prefix=“spring.datasource”)
表示將根據(jù)前綴“spring.datasource”從application.properties中匹配相關(guān)屬性值。
(2)【UserMapper.xml】
Mybatis的sql映射文件。Mybatis同樣支持注解方式,在此不予舉例了。
<?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="cn.no7player.mapper.UserMapper"> <select id="findUserInfo" resultType="cn.no7player.model.User"> select name, age,password from user; </select> </mapper>
(3)接口UserMapper
package cn.no7player.mapper;
import cn.no7player.model.User;
public interface UserMapper {
public User findUserInfo();
}
三、總結(jié)
(1)運行 Application.java
(2)控制臺輸出:
…..(略過無數(shù)內(nèi)容)
(3)訪問:
針對三種控制器的訪問分別為:
視圖:
http://localhost:8080/hello?name=7player
Json:
http://localhost:8080/getUserInfo
Restful(使用了swagger):
http://localhost:8080/swagger/index.html
四、參閱
《Spring Boot – Quick Start》
http://projects.spring.io/spring-boot/#quick-start
《mybatis》
http://mybatis.github.io/mybatis-3/
《使用 Spring Boot 快速構(gòu)建 Spring 框架應(yīng)用》
http://www.ibm.com/developerworks/cn/java/j-lo-spring-boot/
《Using @ConfigurationProperties in Spring Boot》
《Springboot-Mybatis-Mysample》
https://github.com/mizukyf/springboot-mybatis-mysample
《Serving Web Content with Spring MVC》
http://spring.io/guides/gs/serving-web-content/
《理解RESTful架構(gòu)》
http://www.ruanyifeng.com/blog/2011/09/restful
附錄:
Spring Boot 推薦的基礎(chǔ) POM 文件


以上所述是小編給大家介紹的基于SpringBoot與Mybatis實現(xiàn)SpringMVC Web項目,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
SpringMVC日期類型參數(shù)傳遞實現(xiàn)步驟講解
這篇文章主要介紹了SpringMVC日期類型參數(shù)傳遞實現(xiàn)步驟,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-02-02
Java實現(xiàn)文件上傳到服務(wù)器本地并通過url訪問的方法步驟
最近項目中使用到了文件上傳到服務(wù)器的功能,下面這篇文章主要給大家介紹了關(guān)于Java實現(xiàn)文件上傳到服務(wù)器本地并通過url訪問的方法步驟,文中通過圖文以及實例代碼介紹的非常詳細,需要的朋友可以參考下2023-04-04
使用Java實現(xiàn)HTTP和HTTPS代理服務(wù)詳解
這篇文章主要為大家詳細介紹了如何使用Java實現(xiàn)HTTP和HTTPS代理服務(wù),文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-04-04
springboot使用spring-data-jpa操作MySQL數(shù)據(jù)庫
這篇文章主要介紹了springboot使用spring-data-jpa操作MySQL數(shù)據(jù)庫,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07
java連接池Druid獲取連接getConnection示例詳解
這篇文章主要為大家介紹了java連接池Druid獲取連接getConnection示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09

