springboot工程目录
一、简介:讲解SpringBoot常⽤的注解
-
@Controller 作⽤:⽤于标记这个类是⼀个控制器,返回⻚⾯的时候使⽤;如果要返回JSON,则需 要在接⼝上使⽤@ResponseBody才可以
-
@RestController 作⽤:⽤于标记这个类是⼀个控制器,返回JSON数据的时候使⽤,如果使⽤这 个注解,则接⼝返回数据会被序列化为JSON
-
@RestController = @Controller+@ResponseBody
-
@RequestMapping 作⽤:路由映射,⽤于类上做1级路径;⽤于某个⽅法上做⼦路径
-
@SpringBootApplication 作⽤: ⽤于标记是SringBoot应⽤,⾥⾯包含多个⼦注解,@SpringBootApplication = @Configuration+@EnableAutoConfiguration+@ComponentScan
-
@Configuration: 主要标注在某个类上,⽤于spring扫描注⼊,⼀般结合@Bean使⽤
-
@EnableAutoConfiguration: 启⽤Spring的⾃动加载配置,⾃动载⼊应⽤程序所需的所有Bean
-
@ComponentScan:告诉spring扫描包的范围,默认是Applocation类所在的全部⼦包,也可以指定其他包
例如:@ComponentScan({“com.sun.package1”,“com.sun.package2”})
二、springBoot启动方式
1、IDEA开发中启动
2、外置Tomcat中启动
3、jar方式打包启动
- 步骤:pom文件中添加maven插件
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
-
打包启动命令
构建:mvn install 构建跳过测试类 mvn install -Dmaven.test.skip=true target⽬录下有对应的jar包就是打包后项⽬ 进到对应的target⽬录启动 java -jar xxxxx.jar 即可 想后台运⾏,就⽤守护进程 nohup java -jar xxx.jar &
三、springboot中统一接口返回协议
-
JSONData工具类的开发
/* 接口返回工具类 */ public class JsonData { private int code; private Object data; private String msg; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public JsonData(){} public JsonData(int code, Object data){ this.code = code; this.data = data; } public JsonData(int code, Object data, String msg){ this.code = code; this.data =data; this.msg = msg; } public static JsonData buildSuccess(Object data){ return new JsonData(0,data); } public static JsonData buildError(String msg){ return new JsonData(-1,"",msg); } public static JsonData buildError(String msg,int code){ return new JsonData(code,"",msg); } }
四、SpringBoot开发接口请求方式
1、SpringBoot开发Http接口post请求
-
POST请求-form表单
使⽤POST 注解:
@PostMapping = @RequestMapping(method = RequestMethod.POST)
2、JSON对象提交,批量插⼊接⼝
-
POST请求-RequestBody⽅式
-
场景:json对象映射,数组对象提交接⼝开发
注解:
@PostMapping = @RequestMapping(method = RequestMethod.POST}
五、SpringBoot定制json字段。
-
常⽤框架 阿⾥ fastjson, ⾕歌gson等
-
JavaBean序列化为Json
- 性能:Jackson > FastJson > Gson > Json-lib 同个结构 Jackson、FastJson、Gson类库各有优点,各有⾃⼰的专⻓
- 空间换时间,时间换空间
-
jackson处理相关⾃动
-
jackson处理相关⾃动 指定字段不返回:@JsonIgnore (例如:用户密码字段不在显示,只需在密码字段上加上该注解)
-
指定⽇期格式:
@JsonFormat(pattern="yyyy-MM-dd hh:mm:ss",locale="zh",timezone="GMT+8")
-
空字段不返回:@JsonInclude(Include.NON_NULL)
-
指定别名:@JsonProperty
-
-
序列化和反序列化操作
//序列化操作 ObjectMapper objectMapper = new ObjectMapper(); String jsonStr = objectMapper.writeValueAsString(list); System.out.println(jsonStr); //反序列化操作 List<Video> temp = objectMapper.readValue(jsonStr,List.class);
六、spring boot实现热部署
1、什么是热部署?
正在运行的时候升级功能,不需要重新启动应用,相对与java应用的程序员来说,热部署就是在运行期间更新java类文件。
2、好处:
不需要手动启动应用,提高本地开发效率
3、常见启动方式
-
Jrebel Spring
-
Loaded
-
spring-boot-devtools
注意事项:
热部署一般运用在本地开发项目中,上线项目中,为了防止黑客入侵,应减少使用
4、实现热部署步骤
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork><!--必须添加这个配置-->
</configuration>
</plugin>
</plugins>
</build>
idea中配置热部署
使用快捷键打开,选择Register
默认的快捷键
window快捷键 Shift+Ctrl+Alt+/
mac快捷键 Shift+Command+Alt+/
七、认识spring boot里面的配置文件
1、常见配置文件类型
xml,properties,json,yaml
1、xx.yml
展现的是树状结构显示
server:
port: 8080
2、xx.properties
server.port=8080
#配置session失效时间,30m表示30分钟
server.servlet.session.timeout=30m
#配置tomcat最大连接数
server.tomcat.max-connections=10000
# HTTP端口的最大容量
server.tomcat.max-http-form-post-size=2MB
# 最大线程数
server.tomcat.max-threads=200
官⽅⽂档配置
https://docs.spring.io/spring-boot/docs/2.3.0.BUILD-SNAPSHOT/reference/htmlsingle/#
八、springboot注解配置文件映射和实体类
配置文件加载
编写配置文件,例如:xx.properties
方式一:在Controller上⾯配置
1、@PropertySource({“classpath:xx.properties”})
2、增加属性@Value("${test.name}") private String name;
方式二:实体类配置文件(推荐使用)
- 编写config配置类
- 添加@Component注解
- 添加@Configuration
- 使用@PropertySource 注解指定配置文件位置
- 使用@configurationProperties注解,设置相关属性
- 必须通过注⼊IOC对象Resource 进来 , 才能在类中使⽤获取的配置⽂件值。
案例:
@Configuration
@PropertySource(value="classpath:pay.properties")
public class WXConfig implements Serializable {
@Value("${wxpay.appid}")
private String payAppid;
@Value("${wxpay.secret}")
private String paySecret;
@Value("${wxpay.mechid}")
private String payMechId;
public String getPayAppid() {
return payAppid;
}
public void setPayAppid(String payAppid) {
this.payAppid = payAppid;
}
public String getPaySecret() {
return paySecret;
}
public void setPaySecret(String paySecret) {
this.paySecret = paySecret;
}
public String getPayMechId() {
return payMechId;
}
public void setPayMechId(String payMechId) {
this.payMechId = payMechId;
}
}
九、springboot实现单元测试
- 导入依赖
<!--springboot程序测试依赖,如果是⾃动创建项⽬默认添加-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
- 配置相关注解
@RunWith(SpringRunner.class) //底层⽤junit SpringJUnit4ClassRunner
@SpringBootTest(classes={XdclassApplication.class})//启动整个springboot⼯程
public class SpringBootTests { }
-
常见单元测试注解
- @before
- @Test
- @After
1.单元测试调用Controller-service层接口
2.Springboot的MockMvc调⽤api层接口
-
如何测试Controller对外提供的接⼝
-
增加类注解 @AutoConfigureMockMvc
-
注⼊⼀个MockMvc类
-
相关API :
-
perform执⾏⼀个RequestBuilder请求
-
andExpect:添加ResultMatcher->MockMvcResultMatchers验证规则
-
andReturn:最后返回相应的MvcResult->Response
-
-
十、springboot全局异常处理
1、配置全局异常有什么好处?
- 统一错误页面
- 方便用户调试
2.如何配置?
-
类添加注解
- @ControllerAdvice,如果需要返回json数据,则⽅法需要加@ResponseBody
- @RestControllerAdvice, 默认返回json数据,⽅法不需要加@ResponseBody
-
方法添加处理器
- 捕获全局异常
- @ExceptionHandler(value=Exception.class)
注意:@ExceptionHandle统一处理某一类异常,从而减少代码重复率和复杂度
@ControllerAdvice:异常集中处理,更好的使业务逻辑与异常处理剥离开
十一、过滤器、拦截器的使用
1.Springboot2.x里面的过滤器
ApplicationContextHeaderFilter
OrderedCharacterEncodingFilter
OrderedFormContentFilter
OrderedRequestContextFilte
2、使用Servlet3.0的注解开发自定义过滤器
- 注解配置步骤
- 启动类⾥⾯增加 @ServletComponentScan,进⾏扫描
- 新建⼀个Filter类,implements Filter,并实现对应的接⼝
- @WebFilter 标记⼀个类为filter,被spring进⾏扫描
- urlPatterns:拦截规则,⽀持正则
- 控制chain.doFilter的⽅法的调⽤,来实现是否通过放⾏
3.应用场景
- 权限控制
- 用户登录控制
案例:自定义过滤器,返回未登录错误码
private void renderJson(HttpServletResponse response,String json){
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
try(PrintWriter writer = response.getWriter()){
writer.print(json);
}catch (Exception e){
e.printStackTrace();
}
}
Servlet3.0+SpringBoot2.X 注解Listener常⽤监听器
1.监听器类型?
ServletContextListener 应⽤启动监听 HttpSessionLisener 会话监听 ServletRequestListener 请求监听
十二、拦截器(Interceptor)
1.SpringBoot2.x使⽤步骤
-
新建config配置类,实现implements WebMvcConfigurer接口
-
preHandle:调⽤Controller某个⽅法之前
-
postHandle:Controller之后调⽤,视图渲染之前,如果控制器Controller出现了 异常,则不会执⾏此⽅法
-
afterCompletion:不管有没有异常,这个afterCompletion都会被调⽤,⽤于资源清理
2、拦截器不生效问题
-是否有加@Configuration
-拦截路径是否有问题 ** 和 *
- 拦截器最后路径⼀定要 /** 如果是⽬录的话则是 /*/
3.拦截器和Filter过滤器的区别
Filter和Interceptor⼆者都是AOP编程思想的体现,功能基本都可以实现
拦截器功能更强⼤些,Filter能做的事情它都能做
Filter在只在Servlet前后起作⽤,⽽Interceptor够深⼊到⽅法前后、异常抛出前后等
filter依赖于Servlet容器即web应⽤中,⽽Interceptor不依赖于Servlet容器所以可以运⾏在
多种环境。
在接⼝调⽤的⽣命周期⾥,Interceptor可以被多次调⽤,⽽Filter只能在容器初始化时调⽤⼀
次。
Filter和Interceptor的执⾏顺序
过滤前->拦截前->action执⾏->拦截后->过滤后
十三、SpringBoot2.X 整合模板引擎thymeleaf和Freemarker
thymeleaf(**)
1.定义?
轻量级的模板引擎(复杂逻辑业务的不推荐,解析DOM或者XML会占⽤多的内存)
2、官网地址?
官⽹地址:https://www.thymeleaf.org/doc/articles/thymeleaf3migration.html
使用手册:https://www.thymeleaf.org/doc/articles/standarddialect5minutes.html
3.thymeleaf相关maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
4.基本配置
#开发时关闭缓存,不然没法看到实时⻚⾯
spring.thymeleaf.cache=false
spring.thymeleaf.mode=HTML5
#前缀
spring.thymeleaf.prefix=classpath:/templates/
#编码
spring.thymeleaf.encoding=UTF-8
#类型
spring.thymeleaf.content-type=text/html
#名称的后缀
spring.thymeleaf.suffix=.html
Freemarker
1.定义?
FreeMarker Template Language(FTL) ⽂件⼀般保存为 xxx.ftl
严格依赖MVC模式,不依赖Servlet容器(不占⽤JVM内存)
2.使用
<!-- 引⼊freemarker模板引擎的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
3.Freemarker基础配置
# 是否开启thymeleaf缓存,本地为false,⽣产建议为true
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.allow-request-override=false
spring.freemarker.check-template-location=true
#类型
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
#⽂件后缀
spring.freemarker.suffix=.ftl
#路径
spring.freemarker.template-loader-path=classpath:/templates/
3.建立文件夹
1、src/main/resources/templates/fm/user/
2、建⽴⼀个index.ftl
3、user⽂件夹下⾯建⽴⼀个user.html
十四、定时任务
1.定义?
某个时间定时处理某个任务
2.常见的定时任务
Java⾃带的java.util.Timer类 配置⽐较麻烦,时间延后问题
Quartz框架: 配置更简单,xml或者注解适合分布式或者⼤型调度作业
SpringBoot框架⾃带
3、SpringBoot使⽤注解⽅式开启定时任务
1、启动类⾥⾯ @EnableScheduling开启定时任务,⾃动扫描
2、定时任务业务类 加注解 @Component被容器扫描
3、定时执⾏的⽅法加上注解 @Scheduled(fixedRate=2000) 定期执⾏⼀次
4.SpringBoot2.X多种定时任务配置
常⽤定时任务表达式配置和在线⽣成器 cron 定时任务表达式 @Scheduled(cron="*/1 * * * * *") 表示每秒
crontab ⼯具 https://tool.lu/crontab/
fixedRate: 定时多久执⾏⼀次(上⼀次开始执⾏时间点后xx秒再次执⾏;)
fixedDelay: 上⼀次执⾏结束时间点后xx秒再次执⾏
十五、异步任务
异步任务对应于同步任务,同步任务是单线程的,而异步任务对应于多线程的