Spring Boot集成Junit5
- 创建
使用springboot创建就完成集成 - 测试
(1)在Spring Boot项目中使用Junit进行单元测试
PersonService的方法
(2)添加Junit的起步依赖
以前使用junit4
现在,springboot 2.4 自动使用junit5
(3)编写测试类@SpringBootTest
public class TextXxx
在Spring Boot项目中如果编写测试类则必须要在类上面添加@SpringBootTest
2.4.0版本使用Junit5,**不需要加@Runwith**
@SpringBootTest
class Demo02junitApplicationTests {
//查询所有的Person
@Autowired
private IPersonService service;
@Test
void contextLoads() {
service.savePerson();
}
}
SpringBoot整合Hikari数据库连接池
hikari数据库连接池
(1)Hikari
(2)Hikari 是什么?
Hikari是现在比较快,而且轻量的连接池
(3)Hikari 有什么特点
》HikariCP是一款非常强大,高效,并且号称“史上最快连接池”
》在springboot2.0之后,采用的默认数据库连接池就是Hikari。
不需要引入依赖,已经在SpringBoot中包含了。
GitHub地址:https://github.com/brettwooldridge/HikariCP
手动使用hikari
pom.xml
<dependencies>
<!-- jdbc-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<!-- 最快的数据源连接池-->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.4.5</version>
</dependency>
<!-- test-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
</dependencies>
Test01
public class TestHikari {
@Test
public void test01() throws SQLException {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/test01");
config.setUsername("root");
config.setPassword("123456");
HikariDataSource ds = new HikariDataSource(config);
System.out.println(ds.getConnection());
}
@Test
public void test02() throws SQLException {
//直接初始化HikariDataSource
HikariDataSource hds = new HikariDataSource();
hds.setJdbcUrl("jdbc:mysql://localhost:3306/test01");
hds.setUsername("root");
hds.setPassword("123456");
System.out.println(hds.getConnection());
}
}
Spring Boot整合-连接池
(1)数据库连接池hikari配置
只需要在application,yml配置文件中指定数据库相关参数
spring:
datasource: # hikari
driver-class-name: com.mysql.cj.jdbc.Driver # mysql 8
username: root
password: 123456
url: jdbc:mysql://localhost:3306/springboot_test
(2)事务配置
添加事务相关的启动器依赖,mysql相关依赖;
编写业务类UserService使用事务注解@Transactional
Spring Boot集成Mybatis
开发步骤
(1) 添加启动器依赖;(自动添加 使用springboot init…勾选)
(2)配置Mybatis:实体类别名包,日志,映射文件等;注意MySQL8以上版本url连接要加上时区
spring:
datasource: # hikari
driver-class-name: com.mysql.cj.jdbc.Driver # mysql 8
username: root
password: 123456
url: jdbc:mysql://localhost:3306/springboot_test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
mybatis:
type-aliases-package: com.wzx.demo04mybatis.domain #别名
mapper-locations: classpath:com.wzx.demo04mybatis.dao/*.xml #xml文件
#使用注解在启动类上面配置 @MapperScan("com.wzx.demo04mybatis.dao")//存放接口
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #mybatis日志
程序入口加上扫描路径
@SpringBootApplication
@MapperScan("com.wzx.demo04mybatis.dao")//存放接口
public class Demo04mybatisApplication {
public static void main(String[] args) {
SpringApplication.run(Demo04mybatisApplication.class, args);
}
}
Spring Boot集成Mybatis测试
dao
public interface PersonDao {
//全查
List<Person> findAllPersons();
}
mapper
<?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="com.xy.demomybatis.dao.PersonDao">
<select id="findAllPersons" resultType="person">
select * from person
</select>
</mapper>
test
@SpringBootTest
@Slf4j
class DemomybatisApplicationTests {
@Autowired
private PersonDao personDao;
@Test
void contextLoads() {
List<Person> list = personDao.findAllPersons();
list.forEach( p-> log.info("person="+p));
}
}
Spring Boot集成Jpa
(1)添加Spring Data JPA的起步依赖
(2)添加数据库驱动依赖
(3) 在application.yml中配置数据库和jpa的相关属性空格不能随便删除
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver # mysql 8
username: root
password: 123456
url: jdbc:mysql://localhost:3306/crud?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
jpa:
show-sql: true
hibernate:
ddl-auto: update
naming:
physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
database: mysql
测试
@SpringBootTest
class Demojpa2ApplicationTests {
@Autowired
UserDao userDao;
@Test
void test01() {
User user = new User();
user.setGirlFriend("rose");
user.setUsername("jack@xx.com");
user.setName("jack");
userDao.save(user);//--->orm -- >将对象值取出-->sql-->数据库
}
}
@Entity //表示当前类,在数据库有表与它对应
@Table(name = "user")
public class User {
@Id //表示id
@GeneratedValue(strategy = GenerationType.IDENTITY) //主键自增长
private int id;
private String username;
private String password;
private String girlFriend;
private String name;
//继承通用的接口,即可完成增删改查
public interface UserDao extends JpaRepository<User,Integer> {
}
Spring Boot 集成Redis
(1)添加redis的起步依赖
(2) 配置redis的连接信息
spring:
redis:
port: 6379
host: localhost
(3)注入RedisTemplate测试redis操作
@SpringBootTest
class DemoredisApplicationTests {
@Autowired
RedisTemplate<String, String> rt;
@Test
void test01() {
//查找是否有缓存
String json = rt.boundValueOps("cache1").get();
//有就直接返回
if (json != null) {
System.out.println("来自缓存:" + json);
} else {
String json_ = "{name:jack,age:13}";
//没有就先存,再返回
rt.boundValueOps("cache1").set(json_);
System.out.println("保存json " + json_);
}
}
}
SpringBoot2.0 集成 springmvc
整合SpringMVC:端口
(1)可以修改tomcat的端口和访问项目中的静态资源
(2)如何修改tomcat端口
查询Properties/yml
server:
port: 8090
servlet:
context-path: /web01
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver # mysql 8
username: root
password: 123456
url: jdbc:mysql://localhost:3306/saas-export?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
设置配置项(前缀+类变量名)到application配置文件中
private static final string[]CLASSPATH_RESOURCE_LOCATTONS = [ "classpath:/NETA-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"];
整合SpringMVC:静态资源
(1)static目录的作用是什么?
类型webapp,存放静态资源的,如css,js,image
该目录下的资源可以直接访问
http://localhost:8090/js/xxx.js
Spring的注解开发
(1)什么是@Configuration ,@Bean?
》spring提供xml与注解配置bean对象
》xml方式:applicationContext.xml 中配置 <bean …/>
》注解方式:@Configuration
标记在类上,相当于applicationContext.xml@Bean
配置在返回bean对象的方法上,将返回值对象放入ioc容器中
之后可以使用@Autowired
依赖注入
@Configuration
public class MySpringMVCConfiguration implements WebMvcConfigurer {
@Bean //<bean>
public MyInterceptor getMyInterceptor(){
MyInterceptor myInterceptor = new MyInterceptor();
return myInterceptor;
}
// /* 拦截所有 --> MyInterceptor -->preHandle -->true
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getMyInterceptor()).addPathPatterns("/*");
}
}
@Configuration
public class BeanConfig {
@Bean//将当前方法的返回值 放到 ioc容器
public Person getPerson(){
//一般不是@Service @Repository @Controller
Person person = new Person();
person.setName("xy");
person.setAge("21");
return person;
}
}
@SpringBootTest
@Slf4j
class DemospringmvcApplicationTests {
@Autowired
Person person;//从ioc里面取对象
@Test
void test01() {
log.info(" test01 person="+person);
}
}
整合SpringMVC:SpringMVC拦截器
(1)SpringMVC拦截器是什么?
拦截用户对Controller的请求
(2)Springboot中如何开发?
编写拦截器(实现HandlerInterceptor);
//以前是在springmvc.xml中配置,现在的话使用@Configuration加@Bean
@Slf4j
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//拦截器 判断用户是否登录,未登录重定向到登录页
log.info("MyInterceptor preHandle");
return true;//true就是放行 false就是不放行
}
}
编写配置类实现 WebMvcConfigurer,在该类中添加各种组件;
@Configuration
public class MySpringMVCConfiguration implements WebMvcConfigurer {
@Bean //<bean>
public MyInterceptor getMyInterceptor(){
MyInterceptor myInterceptor = new MyInterceptor();
return myInterceptor;
}
// /* 拦截所有 --> MyInterceptor -->preHandle -->true
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getMyInterceptor()).addPathPatterns("/*");
}
}
http://localhost:8090/web01/js/jquery-3.4.1.min
没有经过拦截器的http://localhost:8090/web01/test03
经过拦截器
springboot集成jsp
(1)springboot jsp页面
》添加依赖servlet ,jstl ,JSP引擎
》新建webapp目录(没有该目录不能创建jsp)
》application.properties或者application.yml配置mvc
springboot不建议大家使用jsp,而推荐使用 thymeleaf
大家只能手动添加依赖,并且手动创建webapp目录
pom.xml
<!-- 添加 servlet 依赖. -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- 添加 JSTL(JSP Standard Tag Library,JSP标准标签库) -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- Jasper是tomcat中使用的JSP引擎,运用tomcat-embed-jasper可以将项目与tomcat分开 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
webapp
application.yml
spring:
mvc:
view:
prefix: /WEB-INF/pages/
suffix: .jsp
springboot集成jsp测试
(1)编写Controller
(2)请求转发数据到页面(测试el表达式)
(3)运行要使用spring-boot:run
@Controller
public class PersonController {
@Autowired
HttpServletRequest request;
@RequestMapping(path="/test01",method = {RequestMethod.GET})
public String test01(){
//name jack
request.setAttribute("name","jack");
return "person-list";
}
}
页面
${name}
SpringBoot 集成thymeleaf
Thymeleaf介绍
(1)什么是模板技术?
由模板引擎将数据与模板页面合在一起,形成页面
(2)什么是thymeleaf?
SpringBoot并不推荐使用jsp,但是支持一些模板引擎技术,如:Freemarker,Thymeleaf,Mustache
(3)为什么选择Thymeleaf
可以完全替代jsp
(4)有什么特点
》动静结合,直接访问或者通过服务器访问
浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行
当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示
》开箱即用:它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
》多方言支持:Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
》与SpringBoot完美整合,SpringBoot提供了Thymeleaf的默认配置,并且为Thymeleaf设置了视图解析器,我们可以像以前操作jsp一样来操作Thymeleaf。代码几乎没有任何区别,就是在模板语法上有区别。
Thymeleaf集成
(1)引入启动器
(2)SpringBoot会自动为Thymeleaf注册一个视图解析器:ThymeleafViewResolver
默认前缀:classpath:/templates/
默认后缀:.html
如果我们返回视图:users,会指向到 classpath:/templates/users.html;一般我们无需进行修改,默认即可。
Thymeleaf集成测试
(3)Controller提供数据
使用ModelMap将数据与页面合在一起
@Controller
public class PersonController {
@RequestMapping(path = "tolist")
public String toPersonList(ModelMap map){
List<Person> list = new ArrayList<>();
for (int i = 0; i < 4; i++) {
Person p = new Person();
p.setUsername("xy"+1);
p.setPassword("123456");
list.add(p);
}
map.addAttribute("list",list);
map.addAttribute("name","xy");
return "person-list";
}
}
(4)编写html模板
渲染模型中的数据
注意:把html 的名称空间,改成:xmlns:th="http://www.thymeleaf.org"
会有语法提示
<!DOCTYPE html>
<!--suppress ALL-->
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table>
<p>[[${name}]]</p>
<thead>
<tr>
<th>用户名</th>
<th>密码</th>
</tr>
</thead>
<tbody>
<tr th:each="person:${list}">
<td th:text="${person.username}"></td>
<td th:text="${person.password}"></td>
</tr>
</tbody>
</table>
</body>
</html>
Thymeleaf入门案例说明
${}
:这个类似与el表达式,但其实是ognl的语法,比el表达式更加强大th-
指令:th-是利用了Html5中的自定义属性来实现的。
如果不支持H5,可以用data-th-来代替th:each
:类似于c:foreach 遍历集合,但是语法更加简洁th:text
:声明标签中的文本
例如1,如果user.id有值,会覆盖默认的1
如果没有值,则会显示td中默认的1。
这正是thymeleaf能够动静结合的原因,模板解析失败不影响页面的显示效果,因为会显示默认值!
th-指令语法(查询用)
表达式
(1)Simple expressions:(表达式语法)
Variable Expressions: ${…}:获取变量值;OGNL;
1)、获取对象的属性、调用方法
2)、使用内置的基本对象:
#ctx : the context object.