文章目录
1. SpringBoot 实战
1.1 创建工程
- 打开 IDEA --> Create New Project --> Empty Project --> 填写项目名 --> Finish
- New Module --> Maven --> Next --> 填写项目信息 --> Finish
1.2 引入依赖
<?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>com.zt</groupId>
<artifactId>springboot-demo2</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
1.3 编写基本代码
-
编写引导类
@SpringBootApplication public class Demo2Application { public static void main(String[] args) { SpringApplication.run(Demo2Application.class,args); } }
-
编写 controller
@RestController @RequestMapping("/user") public class UserController { @RequestMapping("/test") public String test() { return "hello SpringBoot"; } }
1.4 整合 SpringMVC
虽然默认配置已经可以使用 SpringMVC 了,不过我们有时候需要进行自定义配置
1.4.1 修改端口号
-
在 resources 中创建 application.properties
-
在 application.properties 中修改端口号
server.port=80
-
打开浏览器访问以下网址
http://localhost/user/test
1.4.2 访问静态资源
现在,我们的项目是一个 jar 工程,那么就没有 webapp,我们的静态资源该放哪里呢?
默认配置中,有一个叫做 ResourceProperties 的类,里面就定义了静态资源的默认查找路径:
默认的静态资源路径为:
- classpath:/META-INF/resources/
- classpath:/resources/
- classpath:/static/
- classpath:/public/
只要静态资源放在这些目录中任何一个,SpringMVC都会帮我们处理,我们习惯会把静态资源放在 classpath:/static/ 目录下
访问静态资源步骤:
-
在 resouces 中创建 static 目录,并且添加一些静态资源(如:a.png)
-
打开浏览器访问以下网址
http://localhost/a.png
1.4.3 添加拦截器
拦截器也是我们经常需要使用的,在 SpringBoot 中该如何配置呢?
-
定义一个拦截器
@Component public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { System.out.println("预处理"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { System.out.println("后处理"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { System.out.println("完成处理"); } }
-
定义配置类,注册拦截器
@Configuration public class MvcConfiguration implements WebMvcConfigurer { @Autowired private MyInterceptor myInterceptor; @Override /** * 重写接口中的 addInterceptors 方法,添加自定义拦截器 */ public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor).addPathPatterns("/**"); } }
-
打开浏览器访问以下网址
http://localhost/user/test
-
查看控制台的打印结果
预处理 后处理 完成处理
1.4.4 修改日志级别
你会发现日志中只有这些打印信息,SpringMVC 的日志信息都没有,因为 SpringMVC 记录的 log 级别是 debug,SpringBoot 默认是显示 info 以上,我们需要修改日志级别
SpringBoot 通过logging.level.*=debug
来配置日志级别,* 填写包名
-
在 application.properties 中修改日志级别
# 设置 org.springframework 包的日志级别为 debug logging.level.org.springframework=debug
-
重启服务器,打开浏览器访问以下网址
http://localhost/user/test
-
查看控制台的打印结果
2019-11-17 17:08:20.333 DEBUG 17412 --- [p-nio-80-exec-4] o.s.web.servlet.DispatcherServlet : GET "/user/test", parameters={} 2019-11-17 17:08:20.334 DEBUG 17412 --- [p-nio-80-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.zt.controller.UserController#test() 预处理 2019-11-17 17:08:20.335 DEBUG 17412 --- [p-nio-80-exec-4] m.m.a.RequestResponseBodyMethodProcessor : Using 'text/html', given [text/html, application/xhtml+xml, image/webp, image/apng, application/signed-exchange;v=b3, application/xml;q=0.9, */*;q=0.8] and supported [text/plain, */*, text/plain, */*, application/json, application/*+json, application/json, application/*+json] 2019-11-17 17:08:20.335 DEBUG 17412 --- [p-nio-80-exec-4] m.m.a.RequestResponseBodyMethodProcessor : Writing ["hello SpringBoot"] 后处理 完成处理 2019-11-17 17:08:20.337 DEBUG 17412 --- [p-nio-80-exec-4] o.s.web.servlet.DispatcherServlet : Completed 200 OK
1.5 整合连接池
-
引入依赖
<!--jdbc 的启动器,默认使用 HikariCP 连接池--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--不要忘记数据库驱动,因为springboot不知道我们使用的什么数据库,这里选择mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
导入 jdbc 启动器后,SpringBoot 就自动帮我们引入了一个连接池 HikariCP,应该是目前速度最快的连接池了
-
在 application.properties 中指定连接池参数
# 连接四大参数 spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_day01?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=123456 # 可省略,SpringBoot自动推断 spring.datasource.driverClassName=com.mysql.jdbc.Driver
1.6 整合 MyBatis
-
引入依赖
<!--mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency>
-
在 application.properties 中指定 MyBatis 配置
# mybatis 别名扫描包 mybatis.type-aliases-package=com.zt.pojo
注意:这里没有配置 mapper 接口扫描包,因此我们需要给每一个 mapper 接口添加
@Mapper
注解,才能被识别 -
创建实体类
public class User implements Serializable { private int id; private String username; private Date birthday; private String sex; private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
-
创建 Mapper 接口
@Mapper public interface UserMapper { @Select("select * from user") List<User> findAll() throws Exception; @Select("select * from user where id = #{id}") User findById(Integer id) throws Exception; @Delete("delete from user where id = #{id}") void deleteById(Integer id) throws Exception; }
1.7 整合事务
-
我们在引入 web 的启动器时,就已经引入事务相关的依赖及默认配置了
-
创建 UserService
@Service public class UserService { @Autowired private UserMapper userMapper; public List<User> findAll() throws Exception { return userMapper.findAll(); } public User findById(Integer id) throws Exception { return userMapper.findById(id); } @Transactional public void deleteById(Integer id) throws Exception { userMapper.deleteById(id); } }
1.8 启动测试
-
在 UserController 中添加测试方法
@RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @RequestMapping("/test") public String test() { return "hello SpringBoot"; } @GetMapping("/findById/{id}") public User findById(@PathVariable("id") Integer id) throws Exception { return userService.findById(id); } @GetMapping("/findAll") public List<User> findAll() throws Exception { return userService.findAll(); } @GetMapping("/deleteById/{id}") public void deleteById(@PathVariable("id") Integer id) throws Exception { userService.deleteById(id); } }
-
打开浏览器访问以下网址
http://localhost/user/findAll
http://localhost/user/findById/52
http://localhost/user/deleteById/52