一,热身
Spring Boot是一个一全新框架。Spring Boot就是用来简化Spring应用的搭建以及开发过程。该框架致力于实现免XML配置,提供便捷,独立的运行环境,实现“一键运行”满足快速应用开发的需求。
补充提示,Spring Boot 推荐采用基于 Java 注解的配置方式,而不是传统的 XML。只需要在主配置 Java 类上添加“@EnableAutoConfiguration”注解就可以启用自动配置。Spring Boot 的自动配置功能是没有侵入性的,只是作为一种基本的默认实现。开发人员可以通过定义其他 bean 来替代自动配置所提供的功能,例如在配置本案例数据源(DataSource)时,可以体会到该用法。
更多基础知识参考
Spring boot 入门helloWorld
二、实践
一些说明:
项目IDE采用IEclipse
工程依赖管理采用个人比较熟悉的Maven(事实上SpringBoot与Groovy才是天生一对)
1.预览:
(1)github地址
https://github.com/lichch/stringboot-mybatis.git
(2)完整项目结构
(3)数据库
数据库名: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', 'lichch', '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>
<version.spring>3.2.9.RELEASE</version.spring>
<version.jackson>2.4.4</version.jackson>
<java.version>1.7</java.version>
</properties>
<dependencies>
<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>
<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>
<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>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!---->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.43</version>
</dependency>
<dependency>
<groupId>com.mangofactory</groupId>
<artifactId>swagger-springmvc</artifactId>
<version>0.9.5</version>
</dependency>
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${version.jackson}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${version.jackson}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${version.jackson}</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路径)
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);
@Bean
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource() {
return new org.apache.tomcat.jdbc.pool.DataSource();
}
@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());
}
/**
* 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下:
package cn.no7player.controller;
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 {
@RequestMapping("/hello")
public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
return "hello";
}
}
(2)Json
返回Json格式数据,多用于Ajax请求。
package cn.no7player.controller;
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;
import cn.no7player.model.User;
import cn.no7player.service.UserService;
/**
*
* ClassName: UserController <br/>
* date: 2017年4月14日 上午10:58:17 <br/>
*
* @author lichch
* @version
* @since JDK 1.7
*/
@Controller
public class UserController {
private Logger logger = Logger.getLogger(UserController.class);
@Autowired
private UserService userService;
@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进阶1 - 整合Swagger2自动生成RESTful API文档》
http://blog.csdn.net/qq_15969757/article/details/70160541
package cn.no7player.controller;
import java.util.ArrayList;
import java.util.List;
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 com.wordnik.swagger.annotations.ApiOperation;
import cn.no7player.model.User;
/**
*
* ClassName: SwaggerController <br/>
* Function: TODO ADD FUNCTION. <br/>
* Reason: TODO ADD REASON(可选). <br/>
* date: 2017年4月13日 下午2:21:00 <br/>
*
* @author lichch
* @version
* @since JDK 1.7
*/
@RestController
@RequestMapping(value = "/users")
public class SwaggerController {
/**
*
* @return
*/
@ApiOperation(value = "查询所有用户", notes = "查询得到所有用户")
@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 = "通过id查询用户", notes = "通过id查询用户")
@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】
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=root
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同样支持注解方式。
<?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();
}
三、总结
(1)运行 Application.java
(2)控制台输出:
开始
运行成功
(3)访问:
针对三种控制器的访问分别为:
视图:
http://localhost:8080/hello?name=7player
Json:
http://localhost:8080/getUserInfo
Restful(使用了swagger):