2、實踐
一些說明:html
項目IDE採用Intellij(主要緣由在於Intellij顏值完爆Eclipse,誰叫這是一個看臉的時代)java
工程依賴管理採用我的比較熟悉的Maven(事實上SpringBoot與Groovy纔是天生一對)mysql
1.預覽:
(1)github地址git
(2)完整項目結構spring
(3)數據庫sql
數據庫名:test mongodb
【user.sql】shell
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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】配置以下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
<?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 應用開發,包含 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 訪問數據庫-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--添加適用於生產環境的功能,如性能指標和監測等功能。 -->
<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.主函數
【Application.java】包含main函數,像普通java程序啓動便可。
此外,該類中還包含和數據庫相關的DataSource,SqlSeesion配置內容。
注:@MapperScan(「cn.no7player.mapper」) 表示Mybatis的映射路徑(package路徑)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
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風格
(1)視圖模板
返回結果爲視圖文件路徑。視圖相關文件默認放置在路徑 resource/templates下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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格式數據,多用於Ajax請求。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
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 指的是一組架構約束條件和原則。知足這些約束條件和原則的應用程序或設計就是 RESTful。
此外,有一款RESTFUL接口的文檔在線自動生成+功能測試功能軟件——Swagger UI,具體配置過程可移步《Spring Boot 利用 Swagger 實現restful測試》
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
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
配置相關代碼在Application.java中體現。
(1)【application.properties】
1
2
3
4
|
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」)
表示將根據前綴「spring.datasource」從application.properties中匹配相關屬性值。
(2)【UserMapper.xml】
Mybatis的sql映射文件。Mybatis一樣支持註解方式,在此不予舉例了。
1
2
3
4
5
6
7
8
9
|
<?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
1
2
3
4
5
6
7
|
package cn.no7player.mapper;
import cn.no7player.model.User;
public interface UserMapper {
public User findUserInfo();
}
|
3、總結
(1)運行 Application.java
(2)控制檯輸出:
…..(略過無數內容)
http://localhost:8080/getUserInfo
Restful(使用了swagger):
4、參閱
《Spring Boot – Quick Start》
http://projects.spring.io/spring-boot/#quick-start
《mybatis》
http://mybatis.github.io/mybatis-3/
《使用 Spring Boot 快速構建 Spring 框架應用》
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架構》
http://www.ruanyifeng.com/blog/2011/09/restful
附錄:
Spring Boot 推薦的基礎 POM 文件
名稱 |
說明 |
spring-boot-starter |
核心 POM,包含自動配置支持、日誌庫和對 YAML 配置文件的支持。 |
spring-boot-starter-amqp |
經過 spring-rabbit 支持 AMQP。 |
spring-boot-starter-aop |
包含 spring-aop 和 AspectJ 來支持面向切面編程(AOP)。 |
spring-boot-starter-batch |
支持 Spring Batch,包含 HSQLDB。 |
spring-boot-starter-data-jpa |
包含 spring-data-jpa、spring-orm 和 Hibernate 來支持 JPA。 |
spring-boot-starter-data-mongodb |
包含 spring-data-mongodb 來支持 MongoDB。 |
spring-boot-starter-data-rest |
經過 spring-data-rest-webmvc 支持以 REST 方式暴露 Spring Data 倉庫。 |
spring-boot-starter-jdbc |
支持使用 JDBC 訪問數據庫。 |
spring-boot-starter-security |
包含 spring-security。 |
spring-boot-starter-test |
包含經常使用的測試所需的依賴,如 JUnit、Hamcrest、Mockito 和 spring-test 等。 |
spring-boot-starter-velocity |
支持使用 Velocity 做爲模板引擎。 |
spring-boot-starter-web |
支持 Web 應用開發,包含 Tomcat 和 spring-mvc。 |
spring-boot-starter-websocket |
支持使用 Tomcat 開發 WebSocket 應用。 |
spring-boot-starter-ws |
支持 Spring Web Services。 |
spring-boot-starter-actuator |
添加適用於生產環境的功能,如性能指標和監測等功能。 |
spring-boot-starter-remote-shell |
添加遠程 SSH 支持。 |
spring-boot-starter-jetty |
使用 Jetty 而不是默認的 Tomcat 做爲應用服務器。 |
spring-boot-starter-log4j |
添加 Log4j 的支持。 |
spring-boot-starter-logging |
使用 Spring Boot 默認的日誌框架 Logback。 |
spring-boot-starter-tomcat |
使用 Spring Boot 默認的 Tomcat 做爲應用服務器。 |