Article Directory
1. SpringBoot combat
1.1 Create Project
- Open IDEA -> Create New Project -> Empty Project -> Fill in the project name -> Finish
- New Module -> Maven -> Next -> Fill Project Information -> Finish
1.2 introducing dependent
<?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 write code base
-
Write the bootstrap class
@SpringBootApplication public class Demo2Application { public static void main(String[] args) { SpringApplication.run(Demo2Application.class,args); } }
-
Write controller
@RestController @RequestMapping("/user") public class UserController { @RequestMapping("/test") public String test() { return "hello SpringBoot"; } }
1.4 Integration SpringMVC
Although the default configuration is ready for use SpringMVC, but sometimes we need to custom configuration
1.4.1 modify the port number
-
Creating the resources in application.properties
-
Modify the port number in application.properties
server.port=80
-
Open your browser to the following URL
http://localhost/user/test
1.4.2 access static resources
Now, our project is a project jar, then there is no webapp, where our static resources that put it?
The default configuration, has called ResourceProperties class, which defines the default search path to static resources:
The default path for the static resources:
- classpath:/META-INF/resources/
- classpath:/resources/
- classpath:/static/
- classpath:/public/
As long as static resources in any of these directories, SpringMVC will help us deal with, we are used to put a static resource in classpath: / static / directory
Access static resources steps:
-
Create a static directory resouces, and add some static resources (such as: a.png)
-
Open your browser to the following URL
http://localhost/a.png
1.4.3 Adding interceptor
Interceptor is what we often need to use, in SpringBoot in how to configure it?
-
Define an interceptor
@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("完成处理"); } }
-
Custom configuration class, registered interceptors
@Configuration public class MvcConfiguration implements WebMvcConfigurer { @Autowired private MyInterceptor myInterceptor; @Override /** * 重写接口中的 addInterceptors 方法,添加自定义拦截器 */ public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor).addPathPatterns("/**"); } }
-
Open your browser to the following URL
http://localhost/user/test
-
Check the print result console
预处理 后处理 完成处理
1.4.4 change the log level
You will find only the print log information, log information SpringMVC are not, because the log record is SpringMVC level debug, SpringBoot default display info above, we need to change the log level
SpringBoot by logging.level.*=debug
configuring log level * Fill in the package name
-
Modify the log level in application.properties
# 设置 org.springframework 包的日志级别为 debug logging.level.org.springframework=debug
-
Restart the server, open the browser to the following URL
http://localhost/user/test
-
Check the print result console
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 Integration Connection Pooling
-
The introduction of dependence
<!--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>
After importing jdbc starter, SpringBoot will automatically help us introduce a connection pool HikariCP, it should be the fastest speed of the connection pool
-
In connection pool parameters specified 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=zt3742 # 可省略,SpringBoot自动推断 spring.datasource.driverClassName=com.mysql.jdbc.Driver
1.6 Integration MyBatis
-
The introduction of dependence
<!--mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency>
-
MyBatis configuration specified in application.properties
# mybatis 别名扫描包 mybatis.type-aliases-package=com.zt.pojo
Note: There is no interface to configure the mapper scan package, so we need to add each interface to a mapper
@Mapper
annotation can be identified -
Creating the Entity Classes
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; } }
-
Creating Mapper Interface
@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 Integration Affairs
-
When we introduced a web-starter, it has been introduced and related dependent on the configuration of the default transaction
-
Creating 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 Test start
-
Add the test method 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); } }
-
Open your browser to the following URL
http://localhost/user/findAll
http://localhost/user/findById/52
http://localhost/user/deleteById/52