一.pom.xml文件
较以往不同的是,springboot的pom文件多出了<parent>标签,该标签配置了springboot的父级依赖。有了这个,当前的项目才是 Spring Boot 项目,spring-boot-starter-parent 是一个特殊的 starter ,它用来提供相关的 Maven 默认依赖,使用它之后,常用的包依赖就可以省去 version 标签。
二.应用入口类
Spring Boot 项目通常有一个名为 *Application 的入口类,入口类里有一个 main 方法, 这个 main 方法其实就是一个标准的 Javay 应用的入口方法。
@SpringBootApplication 是 Spring Boot 的核心注解,它是一个组合注解,该注解组合了:@Configuration、@EnableAutoConfiguration、@ComponentScan; 若不是用 @SpringBootApplication 注解也可以使用这三个注解代替。
- 其中,@EnableAutoConfiguration 让 Spring Boot 根据类路径中的 jar 包依赖为当前项目进行自动配置,例如,添加了 spring-boot-starter-web 依赖,会自动添加 Tomcat 和 Spring MVC 的依赖,那么 Spring Boot 会对 Tomcat 和 Spring MVC 进行自动配置。
- Spring Boot 还会自动扫描 @SpringBootApplication 所在类的同级包以及下级包里的 Bean ,所以入口类建议就配置在 grounpID + arctifactID 组合的包名下(这里为 cn.wmyskxz.springboot 包)
三.Spring Boot 的配置文件
springboot使用的是全局配置文件,名为application.properties。Spring Boot 不仅支持常规的 properties 配置文件,还支持 yaml 语言的配置文件。yaml 是以数据为中心的语言,在配置数据的时候具有面向对象的特征。
四.Spring Boot 热部署
当发现任何类发生了改变,就会通过 JVM 类加载的方式,加载最新的类到虚拟机中,这样就不需要重新启动也能看到修改后的效果了。
往 pom.xml 中添加一个依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional> <!-- 这个需要为 true 热部署才有效 -->
</dependency>
重新启动 Spring Boot ,然后修改任意代码,就能观察到控制台的自动重启现象。
五.Spring Boot 使用
集成 MyBatis
1.修改 pom.xml 增加对 MySql和 MyBatis 的支持
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
2.新增数据库链接参数
3.创建 Student 实体类和 StudentMapper 映射类
新建一个【pojo】包,然后在其下创建一个 Student 类
public class Student {
private Integer id;
private Integer student_id;
private String name;
private Integer age;
private String sex;
private Date birthday;
/* getter and setter */
}
新建一个【mapper】包,然后在其下创建一个 StudentMapper 映射类:
@Mapper
public interface StudentMapper {
@Select("SELECT * FROM student")
List<Student> findAll();
}
4.编写 StudentController
@Controller
public class StudentController {
@Autowired
StudentMapper studentMapper;
@RequestMapping("/listStudent")
public String listStudent(Model model) {
List<Student> students = studentMapper.findAll();
model.addAttribute("students", students);
return "listStudent";
}
}
5.编写 listStudent.jsp 文件
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<table align='center' border='1' cellspacing='0'>
<tr>
<td>id</td>
<td>name</td> </tr>
<c:forEach items="${students}" var="s" varStatus="st">
<tr>
<td>${s.id}</td>
<td>${s.name}</td>
</tr>
</c:forEach>
</table>
6.重启服务器运行
完毕