关于springboot:07SpringBootMyBatisSpring-技术整合实现商品品牌模块的CRUD操作

需要剖析任何一个电商零碎中都有一个商品子系统,而与商品相关联都会有一个品牌信息管理,在以后业务零碎设计中咱们就是要对商品品牌信息进行设计和实现。 业务架构在品牌(Brand)信息管理中就是要实现对商品品牌信息的增加,批改,查问,删除等业务,user是后盾管理员,如图所示 原型设计基于品牌业务形容,对品牌模块的业务原型进行剖析和设计,如图所示 技术架构在品牌治理模块实现郭晨,咱们采纳典型的C/S架构进行实现,客户端咱们基于浏览器实现,服务端采纳Tomcat,数据库应用MySQL,具体应用层基于MVC分成架构进行实现 技术栈选型客户端技术:HTML,CSS,JavaScript,bootstrap服务端技术:spring,mybatis,springboot,thymeleaf数据库:MySql,SQL 数据库及表设计drop database if exists dbbrand;create database dbbrand default character set utf8;use dbbrand;create table tb_brand( id bigint primary key auto_increment, name varchar(100) not null, remark text, createdTime datetime not null)engine=InnoDB;insert into tb_brand values (null,'联想','very good',now());insert into tb_brand values (null,'小米','very good',now());insert into tb_brand values (null,'美的','very good',now());insert into tb_brand values (null,'九阳','very good',now());insert into tb_brand values (null,'TCL','very good',now());insert into tb_brand values (null,'创维','very good',now());insert into tb_brand values (null,'华为','very good',now());我的项目环境初始化筹备操作(1)JDK 1.8(2)Maven 3.6.3(3)IDEA 2020.2(4)MySql 5.7+ ...

November 5, 2020 · 2 min · jiezi

关于springboot:07SpringBootMyBatisSpring-技术整合实现商品品牌模块的CRUD操作

需要剖析任何一个电商零碎中都有一个商品子系统,而与商品相关联都会有一个品牌信息管理,在以后业务零碎设计中咱们就是要对商品品牌信息的治理进行设计和实现. 业务架构在品牌(Brand)信息管理中就是要实现对商品品牌信息的增加,批改,查问,删除等业务,如图所示: 原型设计基于品牌业务形容,对品牌模块的业务原型进行剖析和设计,如图所示: 技术架构在品牌治理模块实现过程,咱们采纳典型的C/S架构进行实现.客户端咱们基于浏览器进行实现,服务端采纳tomcat,数据库应用MySQL.具体应用层基于MVC分层架构进行实现. 技术栈选型客户端技术:html,css,javascript,bootstrap服务端技术:spring,mybatis,springboot,thymeleaf数据库技术:MySQL,SQL数据库及表设计drop database if exists dbbrand;create database dbbrand default character set utf8;use dbbrand;create table tb_brand( id bigint primary key auto_increment, name varchar(100) not null, remark text, createdTime datetime not null)engine=InnoDB;我的项目环境初始化筹备操作1)JDK 1.82)Maven 3.6.33)IDEA 2020.24)MySQL 5.7+ 初始化数据库关上mysql自带客户端,登录mysql. mysql -uroot -proot设置客户端编码 set names utf8;执行sql脚本 source d:/brand.sql创立我的项目Module 增加我的项目Module依赖<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId></dependency><dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>我的项目Module根底配置关上我的项目Module配置文件application.properties,并增加如下内容: server.port=80spring.datasource.url=jdbc:mysql:///dbbrand?serverTimezone=GMT%2B8&characterEncoding=utf8spring.datasource.username=rootspring.datasource.password=rootmybatis.mapper-locations=classpath:/mapper/*/*.xmllogging.level.com.cy=debugspring.thymeleaf.cache=falsespring.thymeleaf.prefix=classpath:/templates/spring.thymeleaf.suffix=.html启动我的项目进行初步环境测试剖析 品牌模块整体API设计 品牌数据的查问及出现业务形容将数据库中的品牌信息查问进去,而后在客户端基于html技术进行出现,如图所示: 服务端查问时序设计 畛域对象(POJO)设计及实现设置Brand对象,基于此对象封装从数据库查问到的品牌信息,代码如下: package com.cy.pj.brand.pojo;import java.util.Date;public class Brand{ private Integer id; private String name; private String remark; private Date createdTime; //.....}数据逻辑对象(DAO)查询方法设计及实现第一步:定义BrandDao接口,代码如下: ...

November 5, 2020 · 1 min · jiezi

关于springboot:lombok的注解了解

@Setter 用于为形容的类生成setter办法,不蕴含final润饰属性。@Getter 用于为形容的类生成getter办法。@ToString 用于为形容的类增加toString办法。@EqualsAndHashCode 用于为形容的类,生成hashCode和equals办法。@NoArgsConstructor 用于为形容的类生成无参的构造方法。@AllArgsConstructor 用于为形容的类生成蕴含类中所有字段的构造方法。@Data用于为形容的类生成setter/getter、equals、canEqual、hashCode、toString办法,如为final属性,则不会为该属性生成setter办法。@Slf4J 用于为形容的类增加一个日志属性对象。

November 4, 2020 · 1 min · jiezi

关于springboot:SpringBoot中的SpringJVM学习总结

MVC为何顾名思义MVC是M(model) V(view) C(controller)是一种软件架构设计思维,将业务分层设计和实现。使程序具备更好的灵活性和可扩展性。 联合操作的简略实例来了解此图像,能够有更好的成果。DispatcherServlet咱们叫它地方控制器,他好比大脑进行整个业务的操控。DispatcherServlet不是由咱们创立,而是由spring底层来创立。 在咱们通过浏览器中输出url进行拜访时DispatcherServlet会把url传给RequestMapping,通过它外部存储url与handler之间的映射关系,用DispatcherServlet传来的url来寻找到对应handler并传回DispatcherServlet。同样RequestMapping也不是咱们而是由底层创立的。 DispatcherMapping将request传给对应的Handler,这个Hanndler是须要要咱们本人去实现。 package com.cy.pj.health.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;@Controller //bean 对象public class TemplateController {//在spring mvc中这个对象称之为handler(处理器) @RequestMapping("doTemplateUI") // @RequestMapping用于定义url申请的映射 public String doTemplateUI(){ return "default";//view name (视图名) }}@RequestMapper("abc")定义通过传入abc来调用此办法。所返回的值便是view name,讲这个值返回给DispatcherServlet。 DispatcherServlet收到所返回的值后将其交给View Resovler View Resovler同样是由底层负责创立,咱们只须要在application.properties中增加咱们所学须要的配置 spring.thymeleaf.prefix=classpath:/templates/spring.thymeleaf.suffix=.htmlView Resovler 减少前缀,后缀,数据。后返回DispatcherServlet。 <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body><h1>The defalut page of templates </h1></body></html>再由DispatherSerlvet响应给用户 ModelAndView利用实例package com.cy.pj.module.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class ModelViewController { @RequestMapping("/doModelAndView") public String doModelAndView(Model model) { model.addAttribute("username", "jason"); model.addAttribute("state", true); return "default"; }}解决完用户申请后,间接将响应数据封装到model中,而后和view一起封装成ModelAndView对象返回给DispatcherServlet。ps.model是底层创立的并且是用map来存储数据。 界面显示代码如下 ...

November 4, 2020 · 1 min · jiezi

关于springboot:动吧dao层及mapper映射文件

创立dao层接口 当mybatis晚期版本,DAO中办法参数多于一个时尽量应用@Param注解进行润饰并指定名字,而后在Mapper文件中便能够通过相似#{username}形式进行获取,否则只能通过#{arg0},#{arg1}或者#{param1},#{param2}等形式进行获取。当初曾经不必这种形式,然而咱们对以前版本做个兼容性创立mapper映射文件来写sql语句在配置文件中mapper门路写的是mapper/*/*.xml所以要在mapper目录下再创立一个目录mapper文件头 <?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">动静sql namespace指定dao全类名sql中,当username不等于null或者空串时查找条件为带username内容的数据当if条件不成立时,where语句也不生成findPageObjects办法sql语句 指定id为办法名,返回后果为SysLog全类名应用下面的共性sql时<include refid="sql的id"></include>排序 依据createdTime降序查找地位 从startIndex开始,pageSize从startIndex开始查几条FAQ:当开始地位为0,查5条的时候,查找的数据是第01234下标的语句,下标是从0开始,如何验证:开始地位为0,查找1条,只能查找出一条sql语句getRowCount办法sql语句 指定id为办法名,返回后果为int,因为dao中返回后果为int

November 4, 2020 · 1 min · jiezi

关于springboot:动吧数据层DOBOVO

日志治理列表数据出现 **数据库中的表记录封装到SysLog对象,所有列即总记录数,SysLog即数据层封装对象 也叫DO/PO业务层把SysLog对象封装到PageObject对象,计算出总页数等,PageObject即业务层数据对象 也叫BO管制层把PageObject对象封装到JsonResult对象,JsonResult对象负责增加状态码等并转成Json对象返回给页面,JsonResult即管制层数据对象 也叫VO分不清也能够统称POJO这里咱们分清创立包,创立po数据层/长久层对象在sys包下创立一个po包 FAQ:序列化和反序列化 把对象转换成字节为序列化 转换为字节,便于在网络上传输,或存储到硬盘内存中 把字节转换成对象为反序列化 倡议所有在java中存储数据的类都实现序列化(Serializable)接口必须创立一个序列化id,否则每次调用都会创立一个新的序列化id创立bo业务层数据对象在sys包下创立一个common/bo包 应用一个类泛型,束缚类中属性,办法参数以及返回值类型例如,当调用这个对象的时候,须要传一个泛型,类中的办法,返回值应用的泛型也主动和类泛型统一

November 4, 2020 · 1 min · jiezi

关于springboot:SpringBoot学习总结Mybatis

Mybaits概述首先mybatis是一个长久层框架,底层基于JDBC与数据交互。springboot会基于mybatis底层框架创立SqlSessionFactory对象,在通过这个工厂对象去创立SqlSession,通过spring框架把sqlsession注入测试类中,从而拜访数据库。 @Mapper用于形容长久层的接口,通知spring框架这个接口的实现类由mybatis创立,并将其交给spring框架治理@Mapper作用于接口上的时候,咱们能够不用手动写出它的实现类,能够节约许多的工夫。然而要留神的是@Mapper润饰的接口不能呈现重名办法,也就是说不能进行办法的重载,这样的话id会反复从而报错。在数据库执行办法较为简便的时候还能够应用全注解开发,在底下办法上增加@Select(sql)进行开发,从而省略xml文件的编写。 实例(蕴含日志记录)创立Goods类 package com.cy.pj.goods.pojo;import java.util.Date;public class Goods { private Long id; private String name; private String remark; private Date createdTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Date getCreatedTime() { return createdTime; } public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; }}创立GoodsMapper.xml配置文件namespace为接口的全门路idwei接口中所应用的办法,resultType为返回的后果集,在本次业务中所填写的是Goods的全门路。如果执行的是增删改操作是,返回的是所扭转的行数,能够不填写resultType。 ...

November 3, 2020 · 1 min · jiezi

关于springboot:SpringBoot学习总结02

Spring 治理bean的劣势应用计算机的目标时进行高效且低耗的计算。对于面向对象语言来说解决问题,须要迷信的使用对象,使之在内存中高效低耗的运行,要达成这样的目标须要肯定的教训,所以咱们须要借助有教训的设计框架,如spring框架。spring框架睁开眼在多个对象协同作用时,低耦合的形式进步其拓展性。 @Qualifier在接口实现类存在多个的时候,在注入@Autowired的同时加上@Qualifier注解指定其注入哪个。 DataSource在java中所有连接池必须恪守datasource标准,能够通过DataSource或缺具体链接池对象。 数据链接池的长处1.资源的重用大大减少连贯创立和敞开的时候的老本2.连贯治理更加的自在用户能够本人依据须要调整,本人所须要的连贯配置3.大大的缩小零碎反应时间缩小创立连贯的工夫,从缩小整体的零碎可能反应时间。 案例 接口的定义 package com.cy.pj.goods.dao;import java.util.List;import java.util.Map;public interface GoodsDao { List<Map<String,Object>> findGoods();}实现类()finally里代码为敞开conn,stat,rs。未写出能够本人封装援用。 package com.cy.pj.goods.dao;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Repository;import javax.sql.DataSource;import java.sql.*;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;@Repositorypublic class DefaultGoodsDao implements GoodsDao{ @Autowired private DataSource dataSource; @Override public List<Map<String, Object>> findGoods() { Connection conn=null; Statement stat=null; ResultSet rs=null; String sql="select * from tb_goods"; List<Map<String,Object>> list=new ArrayList<>(); try{ conn=dataSource.getConnection(); stat=conn.createStatement(); rs=stat.executeQuery(sql); ResultSetMetaData rsmd= rs.getMetaData(); while (rs.next()) { list.add(rowsmap(rsmd, rs)); } return list; }catch (SQLException e){ e.printStackTrace(); return null; }finally{ } } private Map<String,Object> rowsmap(ResultSetMetaData rsmd,ResultSet rs) throws SQLException{ int columnCount = rsmd.getColumnCount(); Map<String,Object> map=new HashMap<>(); for (int i=1;i<=columnCount;i++){ map.put(rsmd.getColumnLabel(i),rs.getObject(i)); } return map; }}测试类 ...

November 2, 2020 · 1 min · jiezi

关于springboot:SpringBoot学习总结

微服务简化部署配置依赖: <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins></build>将这个利用打包成jar包,能够间接应用java -jar 命令运行。 ##POM文件 父我的项目<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.4.RELEASE</version> <relativePath/> </parent>下面的父我的项目是<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.3.4.RELEASE</version></parent>它来治理SpringBoot利用里的所有依赖版本启动器<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>spring-boot-starter-web: spring-boot-starter是springboot的场景启动器,帮咱们导入web依赖。SpringBoot将所有的性能场景都一个个的抽取进去,成为starts(启动器),只须要在我的项目总引入这些start,相干性能场景的所以依赖都会打入进来。 主启动类,主入口类@SpringBootApplicationpublic class SpringbootDemo1Application { public static void main(String[] args) { SpringApplication.run(SpringbootDemo1Application.class, args); }}@SpringBootApplication:此注解标注的类,就是SpringBoot的主配置类,SpringBoot就是通过这个类的main办法启动利用。 @Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@SpringBootConfiguration@EnableAutoConfiguration@ComponentScan( excludeFilters = {@Filter( type = FilterType.CUSTOM, classes = {TypeExcludeFilter.class}), @Filter( type = FilterType.CUSTOM, classes = {AutoConfigurationExcludeFilter.class})})public @interface SpringBootApplication {@SpringBootConfiguration:SpringBoot的配置类 @Configuration: 标注的类为配置类 @Component:@EnableAutoConfiguration:开启主动配置性能 @AutoConfigurationPackage:主动配置包@Import({AutoConfigurationImportSelector.class})@AutoConfigurationPackage@Import({AutoConfigurationImportSelector.class})public @interface EnableAutoConfiguration {将主配置类所在包下及子包下里的说有组件扫描到spring容器 AutoConfigurationImportSelector 导入哪些组件的选择器 SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());SpringBoot在启动的时候从类门路下的META-INF/spring.factories中获取AutoConfiguration指定的值,将这些值作为主动拆卸类导入到容器中,主动拆卸类就失效@AutoConfigurationPackage@Import({AutoConfigurationImportSelector.class})public @interface EnableAutoConfiguration {

November 2, 2020 · 1 min · jiezi

关于springboot:SpringBoot-通过-SSH-通道连接远程-MySQL-数据库

1、增加 Maven 依赖<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version></dependency>2、创立 SSH 连贯工具类import com.jcraft.jsch.JSch;import com.jcraft.jsch.Session;public class SshConnection { //跳板机 String username = "username"; String password = "password"; String host = "host"; int port = 22; //本地端口 int local_port = 3307; String remote_host = "192.168.5.56"; int remote_port = 3306; Session session; /** * 建设SSH连贯 */ public void init() { try { JSch jsch = new JSch(); session = jsch.getSession(username, host, port); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); session.setPortForwardingL(local_port, remote_host, remote_port); } catch (Exception e) { e.printStackTrace(); } } /** * 断开SSH连贯 */ public void destroy() { this.session.disconnect(); }}3、治理 SSH 连贯import org.springframework.stereotype.Component;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import javax.servlet.annotation.WebListener;@WebListener@Componentpublic class SshContextListener implements ServletContextListener { private SshConnection sshConnection; @Override public void contextInitialized(ServletContextEvent arg0) { System.out.println("==========>Context initialized..."); try { sshConnection = new SshConnection(); sshConnection.init(); } catch (Exception e) { e.printStackTrace(); } } @Override public void contextDestroyed(ServletContextEvent arg0) { System.out.println("==========>Context destroyed..."); try { sshConnection.destroy(); } catch (Exception e) { e.printStackTrace(); } }}4、配置 application.propertiesspring.datasource.url=jdbc:mysql://127.0.0.1:3307/test?characterEncoding=utf8spring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driver留神: ...

October 31, 2020 · 1 min · jiezi

关于springboot:动吧整合环境准备

本文章基于原作者@Jason编写,仅用于集体学习 创立数据库,利用分层等步骤省略 创立一个我的项目,增加如下依赖 创立一个application.yml文件或把application.properties的后缀名改为yml 在yml外面配置 url中如果端口号为3306的话能够把localhost:3306简写为/ context-path的作用 默认加/,如果在/前面加内容的话,例如/dd那么拜访门路就是localhost:端口号/dd/拜访门路 thymeleaf thymeleaf设置不能间接拜访的页面cache是设置缓存,为true时批改页面只能重新启动才会显示批改的页面,为false则刷新即可prefix为前缀,mybatis configuration default-statement-timeout:30为超时工夫 map-underscore-to-camel-case:true为驼峰命名法 例如数据库中的user_name能够间接映射到pojo对象的username mapper-locations:classpath:/mapper/*/*.xml为mapper映射门路LOG com.cy: debug com.cy包下的日志

October 31, 2020 · 1 min · jiezi

关于springboot:SpringBoot-DB-系列Redis-高级特性之发布订阅

【SpringBoot DB 系列】Redis 高级个性之公布订阅通常来讲,当咱们业务存在音讯的业务逻辑时更多的是间接应用成熟的 rabbitmq,rocketmq,然而一些简略的业务场景中,真的有必要额定的引入一个 mq 么?本文将介绍一下 redis 的公布订阅形式,来实现繁难的音讯零碎逻辑 <!-- more --> I. 根本应用1. 配置咱们应用 SpringBoot 2.2.1.RELEASE来搭建我的项目环境,间接在pom.xml中增加 redis 依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId></dependency>如果咱们的 redis 是默认配置,则能够不额定增加任何配置;也能够间接在application.yml配置中,如下 spring: redis: host: 127.0.0.1 port: 6379 password:2. 应用姿态redis 的公布/订阅,次要就是利用两个命令publish/subscribe; 在 SpringBoot 中应用公布订阅模式比较简单,借助 RedisTemplate 能够很不便的实现 a. 音讯公布@Servicepublic class PubSubBean { @Autowired private StringRedisTemplate redisTemplate; public void publish(String key, String value) { redisTemplate.execute(new RedisCallback<Object>() { @Override public Object doInRedis(RedisConnection redisConnection) throws DataAccessException { redisConnection.publish(key.getBytes(), value.getBytes()); return null; } }); }}b. 订阅音讯音讯订阅这里,须要留神咱们借助org.springframework.data.redis.connection.MessageListener来实现生产逻辑 ...

October 30, 2020 · 2 min · jiezi

关于springboot:springboot-空值不返回

1、全局配置 spring.jackson.default-property-inclusion=non_null2、部分应用 @JsonInclude(JsonInclude.Include.NON_NULL) public class OrderTransport { private String name; private Integer age;}

October 30, 2020 · 1 min · jiezi

关于springboot:如何理解-Spring-Boot技术

如何了解 Spring Boot技术?Spring Boot 背景剖析JAVAEE利用体系中沉重的配置、低下的开发效率、高难度的三方集成,简单的部署流程等等始终被开发人员所诟病。即便是应用Spring这样的轻量级的资源整合框架,在实现其绝对比拟多的资源整合时,仍旧须要大量的手动依赖治理,简单的XML配置(还常常没有提醒)。还有就是当初的软件生态利用也曾经造成肯定的规模,零碎架构正在从单体架构,分布式架构,逾越到微服务架构。随着整个架构体系的变动,企业对技术的要求也在变动,当初的企业更重视技术的开箱即用,更重视技术在生态圈中的深度交融,更重视轻量级的运维。由此由此spring boot诞生。Spring Boot 要解决什么问题Spring Boot是由Pivotal团队提供的全新的Java软件开发框架(很多人当初把它了解为一个脚手架),其设计目标是用来简化Spring我的项目的初始搭建以及开发过程。该框架应用了特定的注解形式来进行配置,从而使开发人员不再须要大量的xml配置。不再须要大量的手动依赖治理。Spring Boot基于疾速构建理念,通过约定大于配置,开箱即用的形式,心愿可能在蓬勃发展的疾速利用开发畛域成为其领导者。Spring Boot 有哪些外围的要害个性起步依赖(Starter Dependency)。主动配置(Auto Configuration)。健康检查(Actator)-监控。嵌入式服务(Tomcat,Jetty)。总结(Summary)总之,Spring Boot 框架就是要基于疾速构建理念,基于约定大于配置形式,实现技术的开箱即用,以进步开发效率。

October 30, 2020 · 1 min · jiezi

关于springboot:springboot-i18n-国际化

介绍客户端通过Accept-Language管制国际化显示。 messageSourcegetMessage(String code, Object[] args, String defaultMessage, Locale locale)getMessage(String code, Object[] args, Locale locale)getMessage(MessageSourceResolvable resolvable, Locale locale)应用1、springboot自带国际化,不须要独自引入依赖。 2、在resource下新建 i18n/messages.properties 3、在启动配置文件减少以下内容 properties配置# locale 国际化spring.messages.basename=i18n/messagesspring.messages.encoding=UTF-8yml配置# locale 国际化spring: messages: basename: i18n/messages encoding: UTF-84、在应用的类中引入 MessageResource @ControllerAdvicepublic class GlobalExceptionHandler { @Autowired private MessageSource messageSource; private String getLocaleMessage(HttpServletRequest request, String code, Object[] msgArg) { Locale locale = RequestContextUtils.getLocale(request); if(locale == null){ locale = Locale.US; } return messageSource.getMessage(code, msgArg, locale); }}5、在动态类中应用 public static BaseResponse success(HttpServletRequest request, String requestId, Object object){ ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setCacheSeconds(-1); messageSource.setDefaultEncoding(StandardCharsets.UTF_8.name()); messageSource.setBasenames("/i18n/messages"); Locale locale = RequestContextUtils.getLocale(request); String code = ErrorCode.SUCCESS; String message = messageSource.getMessage(code, null, locale); BaseResponse res = new BaseResponse(); res.setRequestId(requestId); res.setCode(code); res.setMessage(message); res.setData(object); return res;}

October 30, 2020 · 1 min · jiezi

关于springboot:springboot注解

validation注解罕用注解@Null 被正文的元素必须为null@NotNull 被正文的元素不能为null,但能够为empty,没有Size的束缚@AssertTrue 被正文的元素必须为true@AssertFalse 被正文的元素必须为false@Min(value) 被正文的元素必须是一个数字,其值必须大于等于指定的最小值@Max(value) 被正文的元素必须是一个数字,其值必须小于等于指定的最大值@DecimalMin(value) 被正文的元素必须是一个数字,其值必须大于等于指定的最小值@DecimalMax(value) 被正文的元素必须是一个数字,其值必须小于等于指定的最大值@Size(max,min) 被正文的元素的大小必须在指定的范畴内。@Digits(integer,fraction) 被正文的元素必须是一个数字,其值必须在可承受的范畴内@Past 被正文的元素必须是一个过来的日期@Future 被正文的元素必须是一个未来的日期@Pattern(value) 被正文的元素必须合乎指定的正则表达式。@Email 被正文的元素必须是电子邮件地址@Length 被正文的字符串的大小必须在指定的范畴内@NotEmpty 被正文的字符串必须非空,不能为null,且Size>0@Range 被正文的元素必须在适合的范畴内@NotBlank 只用于String,不能为null且trim()之后size>0应用@Validated验证。 应用@RequestBody验证body数据。 举例UsersControllerpackage com.chenglulu.controller.users;import org.springframework.http.MediaType;import org.springframework.validation.annotation.Validated;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest;@RestController@RequestMapping( value = "/", produces = {MediaType.APPLICATION_JSON_VALUE})public class UsersController { @RequestMapping(value = "/register", method = RequestMethod.POST) public void registerUser(HttpServletRequest request, @Validated @RequestBody RegisterUsersParams params){ }}RegisterUsersParamspackage com.chenglulu.controller.users.domain;import com.chenglulu.constant.Validation;import lombok.Data;import javax.validation.constraints.NotBlank;import javax.validation.constraints.NotNull;import javax.validation.constraints.Pattern;@Datapublic class RegisterUsersParams { @NotBlank(message = "username is blank") private String username; @NotBlank(message = "phone is blank") @Pattern(regexp = Validation.PHONE) private String phone; @Email private String email;}全局异样解决罕用注解@ControllerAdvice@ExceptionHandler 异样类型@ResponseStatus 异样响应状态@ResponseBody举例package com.chenglulu.exception;import com.chenglulu.constant.Constants;import com.chenglulu.constant.ErrorCode;import com.chenglulu.controller.users.domain.BaseResponse;import com.chenglulu.utils.ResponseUtil;import org.apache.commons.lang3.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.MessageSource;import org.springframework.core.MethodParameter;import org.springframework.http.HttpEntity;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.validation.BindingResult;import org.springframework.validation.FieldError;import org.springframework.web.bind.MethodArgumentNotValidException;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.ResponseStatus;import org.springframework.web.servlet.support.RequestContextUtils;import javax.servlet.http.HttpServletRequest;import java.util.List;import java.util.Locale;@ControllerAdvicepublic class GlobalExceptionHandler { @Autowired private MessageSource messageSource; /** * 未知异样解决 * @param request 申请 * @param ex 异样对象 */ @ExceptionHandler(value = {MethodArgumentNotValidException.class}) @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ResponseBody public HttpEntity<BaseResponse> handlerMethodArgumentNotValidException(HttpServletRequest request, MethodArgumentNotValidException ex){ String requestId = getRequestIdHeader(request); String code = ErrorCode.PARAMETER_ERROR; Locale locale = RequestContextUtils.getLocale(request); BindingResult br = ex.getBindingResult(); StringBuilder msgStr = new StringBuilder(); List<FieldError> feList = br.getFieldErrors(); for (FieldError fe : feList) { String message = fe.getDefaultMessage(); String field = fe.getField(); msgStr.append(field).append(message).append("; "); } Object[] msgArg = new Object[]{msgStr}; String message = messageSource.getMessage(code, msgArg, locale); BaseResponse res = ResponseUtil.error(requestId, code, message); return new HttpEntity<BaseResponse>(res); } /** * 未知异样解决 * @param request 申请 * @param ex 异样对象 */ @ExceptionHandler(value = {Exception.class}) @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) @ResponseBody public HttpEntity<BaseResponse> handlerException(HttpServletRequest request, Exception ex){ String requestId = getRequestIdHeader(request); String code = ErrorCode.UNKNOWN_ERROR; BaseResponse res = ResponseUtil.error(request, requestId, code, null); return new HttpEntity<BaseResponse>(res); } private String getRequestIdHeader(HttpServletRequest request) { return request.getHeader(Constants.HEADER_X_REQUEST_ID); } private String getLocaleMessage(HttpServletRequest request) { }}

October 30, 2020 · 2 min · jiezi

关于springboot:SpringBoot的用法回顾

1.1 对于SpringBoot配置文件的阐明1.1.1 properties阐明1.语法:K-V构造 key=value2.数据类型:默认是String数据类型,不要增加多余的""号3.字符数据类型:properties的默认的加载的编码格局为ISO-8859-1,所以增加中文是须要字符转意。4.毛病:所有额key都不许手动的编辑,没有方法复用,所以就引入yml配置 1.1.2 YML的配置文件的阐明1.语法:K-V构造 在写法上:key:value 本质上key=valuekey:value 两头应用(:+空格)分隔key与key之间是有父子级关系,所有写的时候须要缩进项。YML配置文件默认的格局都是UTF-8编码,所以能够间接编译中文 1.2 对于SpringMVC调用流程(理解)1.2.1 常识的扫盲1.协定的反对:http协定/https协定(OSI7层网络模型,物数网传会表应) 2.Java针对于服务器端开发了一种传输机制 Servlet机制(TCP-IP协定标准) 用户应用servlet进行数据的传输的速度是比拟快的。 1.2.2 SpringMVC调用流程 1.组件: 1.1 DispatcherServlet 前端控制器(所有申请的中转站)1.2 HandlerMapping 处理器映射器(将用户的申请与执行的业务办法进行映射(绑定))1.3 HandlerAdaptor 处理器适配器1.4 ViewReslover 视图解析器 1.2 对于配置文件赋值操作1.2.1 属性赋值操作需要:又是对象中的属性的值可能会发生变化,如果间接写死在代码中可能会导致耦合性高,是否利用配置文件形式动静的为属性赋值。 1.2.2 利用properties文件为属性赋值阐明:因为YML配置文件个别都是配置第三方的整合的信息,如果将业务的数据增加到YML中则不标准,最好将业务的操作增加到properties文件中编辑RedisPro配置文件: 1.3 SpringBoot环境切换问题业务场景:员工是外包人员,经常性的须要往返公司和甲方,进行代码调试时因为地位不同所以服务器IP地址必然不同,如果每次换环境都不许从新编辑IP地址和端口等数据,必然是繁琐的步骤,那是否能够优化?? 1.3.1 业务实现-指定多个环境注意事项:无论什么样的环境,配置的个数都是雷同的,只有值不同... 1.4 IDEA增加热部署配置1.增加jar包文件2.配置IDEA工具 组合键:ctrl + shift + alt + /2.1 开启主动编译即可 1.5 SpringBoot整合Mybatis1.5.1 编辑pom.xml文件 1.5.2 编辑POJO 1.5.3 对于LomBok问题:java我的项目开发实现之后须要在Linux零碎中部署我的项目。那么在Linux环境中是否须要独自装置对于LomBok插件?? 考点:LomBok插件工作原理是否分明...A:须要 B:不须要答案:B解析:LomBok插件编译器无效 xxx.java文件---编译---xxx.class动静的生成set/get/toString等办法增加到.class文件中即可。Linux中运行的jar包是.class文件的汇合,曾经有了get/set办法,所以不须要引入插件1.5.4 对于Sql连贯阐明1.serverTimezone=GMT%2B8 %2B 代表 "+"号 示意时区2.useUnicode=true&characterEncoding=utf8 指定编码为utf-83.autoReconnect=true& 如果程序连贯数据库中途断掉时是否重连.4.allowMultiQueries=true 是否容许批量操作eg: 要求一次入库3张表数据… 要求用一行sql实现该操作 ...

October 29, 2020 · 1 min · jiezi

关于springboot:如何理解Spring中的Autowired

@Autowired 简介@Autowired 注解用于形容类中的属性,构造方法,set办法,配置办法等,用于通知Spring框架依照指定规定为属性注入值(DI)。 @Autowired 利用入门基于如下API设计,进行代码实现进而剖析@Autowired利用剖析。 第一步:设计Cache接口 package com.cy.pj.common.cache;public interface Cache { }第二步: 设计Cache接口实现类WeakCache,并交给spring治理。 package com.cy.pj.common.cache; import org.springframework.stereotype.Component; @Component public class WeakCache implements Cache{ }第二步: 设计Cache接口实现类SoftCache,并交给spring治理。 package com.cy.pj.common.cache; @Componentpublic class SoftCache implements Cache{…}第三步:设计单元测试类 package com.cy.pj.common.cache;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest public class CacheTests { @Autowired @Qualifier("softCache") private Cache cache; @Test public void testCache() { System.out.println(cache); }}基于单元测试,剖析@Autowired利用(底层通过反射技术为属性赋值)。 阐明:Spring框架在我的项目运行时如果发现由他治理的Bean对象中有应用@Autowired注解形容的属性,能够依照指定规定为属性赋值(DI)。其根本规定是:首先要检测容器中是否有与属性类型相匹配的对象,如果有并且只有一个则间接注入。其次,如果检测到有多个,还会依照@Autowired形容的属性名查找是否有名字匹配的对象,有则间接注入,没有则抛出异样。最初,如果咱们有明确要求,必须要注入类型为指定类型,名字为指定名字的对象还能够应用@Qualifier注解对其属性或参数进行形容(此注解必须配合@Autowired注解应用)。@Autowired 利用进阶@Autowired 注解在Spring治理的Bean中也能够形容其构造方法,set办法,配置办法等,其规定仍旧是先匹配办法参数类型再匹配参数名,基于如下图的设计进行剖析和实现: 第一步:定义SearchService类并交给Spring治理 package com.cy.pj.common.service;@Componentpublic class SearchService{ private Cache cache; @Autowired public SearchService(@Qualifier("softCache")Cache cache){ this.cache=cache; } public Cache getCache(){ return this.cache; }}@Qualifier能够形容构造方法参数,但不能够形容构造方法。第二步:定义SearchServiceTests单元测试类。 ...

October 29, 2020 · 1 min · jiezi

关于springboot:如何理解Spring框架中的Bean对象

Bean对象的定义?在Spring框架中由Spring创立和治理的对象的对象称之为Bean对象。 Bean对象的个性?Spring框架为了更加迷信的治理和利用Bean对象,为其设计相干个性,例如:懒加载、作用域以及生命周期办法。 懒加载(Lazy)在Spring框架中,默认会在启动时会创立所有的Bean对象,但有些bean对象如果长时间不必,启动时就创建对象,会占用其内存资源,从而造成肯定的资源节约,此时咱们能够基于懒加载策略提早对象的创立,在设计类时,在类上增加@Lazy注解,例如: package com.cy.pj.common.pool;@Component@Lazypublic class ObjectPool { public ObjectPool() { System.out.println("ObjectPool()"); }}其中,@Lazy注解中有一个value属性,其默认值为true示意提早加载。作用域(Scope)Spring框架创建对象当前,能够给对象一个作用域,目标是让对象在肯定范畴内能够进行重用,罕用有单例(singleton)和多例(prototype)两种,其中: singleton:此作用域指的是,名字和类型雷同的Bean对象实例在整个Spring容器中只能一份。此实例何时创立与类的提早加载个性配置无关,此实例创立当前,生命周期会由spring框架治理。prototype:此作用域指的是,每次从Spring容器获取对象都会创立新实例,此实例会在须要时创立与lazy个性无关,这个实例创立当前,spring能够对其初始化,但不负责销毁。基于注解@Scope形式设定Bean作用域,代码演示: package com.cy.pj.common.pool;、@Lazy@Scope("singlton")@Componentpublic class ObjectPool { public ObjectPool() { System.out.println("ObjectPool()"); }}Spring中默认bean对象的作用域为singleton,如果心愿是prototype能够应用@Scope("prototype")生命周期办法程序中每个对象都有生命周期,但不是每个对象类型定义时,都要定义生命周期办法,当一个Bean对象创立当前如果还需执行额定初始化,销毁之前也须要额定的其它资源的开释,Spring框架能够为类定义其生命周期办法。如果是注解形式,咱们能够采纳如下两个注解进行实现。 @PostConstruct 注解用于形容bean对象生命周期办法中的初始化办法,此办法会在对象的构造方法之后执行(是对象创立当前的初始化)。@PreDestroy 注解用于形容Bean对象生命周期办法中的销毁办法,此办法会在对象销毁之前执行(当作用域为prototype时,此办法不会执行)。代码演示: package com.cy.pj.common.pool;、@Lazy@Scope("singlton")@Componentpublic class ObjectPool { public ObjectPool() { System.out.println("ObjectPool()"); } @PostConstruct public void init() { System.out.println("init()"); } @PreDestroy public void close() { System.out.println("close()"); }}个别池对象都会设置一些生命周期办法,例如连接池。总结(Summary)本大节次要对Spring框架中的Bean对象个性做了一个概要剖析,能够通过这个剖析理解Spring框架是如何迷信利用bean对象的。

October 29, 2020 · 1 min · jiezi

关于springboot:SpringBoot高级用法

SpringBoot配置文件properties配置文件语法:key-value构造 key=value数据类型:默认是String字符数据类型:properties默认的加载编码的格局为IOS-8859-1毛病:所有的key都必须手动编辑yml配置文件语法:key-value构造 写法上key:value加载编码的格局为UTF-8spring: thymeleaf: prefix: templates/ suffix: .htmlSpringMVC解决流程四大组件前端控制器(DispatcherServlet)映射适配器(HandlerMapping)控制器适配器(HandlerAdaptor)视图解析器(ViewReslover) @RequestController@Controller+@ResponseBody将返回值转换为JSON串应用,程序将不会执行视图解析器 @Controller返回类型为String或modleAndView

October 29, 2020 · 1 min · jiezi

关于springboot:SpringBoot系列1快速搭建web-api项目

内容概述SpringBoot最常见得用处就是web api我的项目。 本文介绍应用主动配置性能,通过最简洁的pom依赖,疾速搭建一个示例我的项目。 实现的性能为:接管http申请并返回json格局的数据。 1. 须要的pom依赖SpringBoot的一大特色就是主动配置,通过主动配置,能够极大简化pom.xml,和代码量。 一个简略的web api我的项目须要的性能是:解决http申请,读写mysql。在理论我的项目中,根本都会应用mysql连接池和sql解析工具,进步性能和开发效率。这里应用了druid + mybatis-plus 依照约定,主动配置的包名称个别蕴含starter。本我的项目中应用的starter如下: web的starter,包含对tomcat的主动配置,因为我的项目中应用了Springboot的parent,所以这里不必指定版本<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>druid的starter,用来主动配置连接池,用于mysql的连贯<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.1</version></dependency>mybatis-plus的starter,用来加载mapper类等依赖<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.1</version></dependency>2. 配置信息应用主动配置时,个别通过SpringBoot的配置文件application.yml,自定义各种参数。本我的项目中用到的配置为mysql连贯信息和web我的项目启动端口,具体如下: spring: datasource: druid: url: jdbc:mysql://localhost:3306/test_db?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC username: root password: 123456server: port: 8999通过应用druid-spring-boot-starter,启动时会依据mysql配置,主动生成连贯,用于mysql拜访。port指定web拜访的端口,api我的项目中通常会抉择非80端口3. 代码阐明为了进步开发效率,我的项目中应用mybatis-plus-generator,生成读写表所需的entity,mapper和service类。 为了与前端开发更无效的配置,通常web api我的项目中会应用一个对立返回类来管制返回值格局,保障接口返回的格局对立。 除了生成的代码外,我的项目中只须要实现对立格局类CommonResVo,和控制器类UserController即可提供api拜访,目录如下: 源码地址:https://gitee.com/dothetrick/... 以上内容属集体学习总结,如有不当之处,欢送在评论中斧正

October 26, 2020 · 1 min · jiezi

关于springboot:SpringBoot使用jsr303校验

依赖增加<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId></dependency>一些较老版本的SpringBoot须要增加相干依赖,我应用的2.1.4发行版不必这个操作。 验证应用对象接管参数的状况public class PointDeductSetRequest { private Long id; @NotBlank(message = "租户id为空") private String tenantId; private Integer status; @NotNull private Integer pointValue; @NotNull private Integer deductValue; @NotBlank(message = "操作员id为空") private String operator;}首先在须要验证的对象的对应字段上方加上校验注解,以下为一些罕用注解:@Null 限度只能为null@NotNull 限度必须不为null@AssertFalse 限度必须为false@AssertTrue 限度必须为true@DecimalMax(value) 限度必须为一个不大于指定值的数字@DecimalMin(value) 限度必须为一个不小于指定值的数字@Digits(integer,fraction) 限度必须为一个小数,且整数局部的位数不能超过integer,小数局部的位数不能超过fraction@Future 限度必须是一个未来的日期@Max(value) 限度必须为一个不大于指定值的数字@Min(value) 限度必须为一个不小于指定值的数字@Past 限度必须是一个过来的日期@Pattern(value) 限度必须合乎指定的正则表达式@Size(max,min) 限度字符长度必须在min到max之间@Past 验证注解的元素值(日期类型)比以后工夫早@NotEmpty 验证注解的元素值不为null且不为空(字符串长度不为0、汇合大小不为0)@NotBlank 验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只利用于字符串且在比拟时会去除字符串的空格@Email 验证注解的元素值是Email,也能够通过正则表达式和flag指定自定义的email格局 @RequestMapping(value = "/deduct", method = RequestMethod.POST)public BusinessResponse setPointDeduct(@RequestBody @Valid PointDeductSetRequest request){ pointDeductService.setPointDeductRule(request); return new BusinessResponse(ResponseEnum.OK);}之后在controller办法的对象参数前加@Valid注解。 校验应用单个参数承受的状况@RequestMapping(value = "/deduct", method = RequestMethod.GET)public PageResponse<TPointDeduct> getPointDeductList(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "pageSize", required = false) Integer pageSize, @RequestParam(value = "tenantId", required = false) @NotBlank(message = "租户id为空") String tenantId, @RequestParam(value = "status", required = false) Integer status){ PageResponse<TPointDeduct> response = pointDeductService.getPointDeductList(page, pageSize, tenantId, status); response.setCodeMsg(ResponseEnum.OK); return response;}首先须要在controller类上加@Validated注解,之后在办法中须要校验的参数前加上对应的校验注解进行校验。 ...

October 26, 2020 · 1 min · jiezi

关于springboot:Spring-Aop-动态代理

1.代理模式代理是设计模式的一种,代理类为委托类提供音讯预处理,音讯转发,预先音讯解决等性能。Java中的代理分为三种角色: 代理类、委托类、接口。 为了放弃行为的一致性,代理类和委托类通常会实现雷同的接口,所以在访问者看来两者没有丝毫的区别。通过代理类这两头一层,能无效管制对委托类对象的间接拜访,也能够很好地暗藏和爱护委托类对象,同时也为施行不同控制策略预留了空间,从而在设计上取得了更大的灵活性。Java 动静代理机制以奇妙的形式近乎完满地实际了代理模式的设计理念。 Java中的代理依照代理类生成机会不同又分为动态代理和动静代理: 动态代理:动态代理的特点是, 为每一个业务加强都提供一个代理类, 由代理类来创立代理对象. 上面咱们通过动态代理来实现对转账业务进行身份验证.动静代理:动态代理会为每一个业务加强都提供一个代理类, 由代理类来创立代理对象, 而动静代理并不存在代理类, 代理对象间接由代理生成工具动静生成.1.2.动态代理Java中的动态代理要求代理类(ProxySubject)和委托类(RealSubject)都实现同一个接口(Subject)。如下示例: 接口 Subject.javapublic interface Subject { public void sayHello(); }委托类 RealSubject.javapublic class RealSubject implements Subject { @Override public void sayHello() { System.out.println("hello!"); } }代理类 ProxySubject.javaclass ProxySubject implements Subject { private Subject subject; public ProxySubject(Subject subject) { this.subject = subject; } @Override public void sayHello() { System.out.println("Before say hello..."); subject.sayHello(); System.out.println("After say hello..."); } }测试方法 main public static void main(String[] args) { Subject subject = new RealSubject(); ProxySubject proxySubject = new ProxySubject(subject); proxySubject.sayHello(); }依照示例中,代理模式实现的性能,能够了解成一个简易版的Spring AOP 实现,那咱们就拿代理模式和Spring AOP做比照。 ...

October 25, 2020 · 2 min · jiezi

关于springboot:SpringBoot

待欠缺

October 25, 2020 · 1 min · jiezi

关于springboot:02第四阶段内容

整合mtbatis plus这个是pom依赖<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.com.jt.jt</groupId> <artifactId>springboot_demo2_mybatis</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot_demo2_mybatis</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <!--引入插件lombok 主动的set/get/构造方法插件 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!--引入数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!--springBoot数据库连贯 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--spring整合mybatis-plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.2.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project>dao层接口 须要继承BaseMapper<User> 能力应用MP工具/@Mapper //将接口交给Spring治理public interface UserDao extends BaseMapper<User> { //查问user表的所有的记录 @Select("select * from user") List<User> findAll();}pojo层 设置办法@Data@Accessors(chain = true)@TableName //("user") //1.将对象与表 进行一对一关联public class User implements Serializable { @TableId(type = IdType.AUTO) //主键的信息 设定自增 private Integer Id; //@TableField("name") //如果字段名称与属性的名称统一(蕴含驼峰规定),能够省略不写 private String name; private Integer age; private String sex;}加这个注解能够间接 不必在dao层加mappr单注解了@SpringBootApplication@MapperScan("com.com.jt.jt.dao") //次要通知mapper的包门路,会主动的实现包扫描public class SpringbootDemo2MybatisApplication { public static void main(String[] args) { SpringApplication.run(SpringbootDemo2MybatisApplication.class, args); }}xml总配置server: port: 8090 #定义端口 servlet: context-path: / #定义我的项目的公布门路spring: datasource: #driver-class-name: com.mysql.cj.jdbc.Driver springboot程序采纳默认的配置 url: jdbc:mysql://127.0.0.1:3306/jtdb?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true username: root password: rootmybatis-plus: #定义别名包 type-aliases-package: com.com.jt.jt.pojo #加载user标签的mapper文件 mapper-locations: classpath:/mybatis/mappers/*.xml #开启驼峰映射 configuration: map-underscore-to-camel-case: true#引入日志信息.logging: level: com.jt.dao: debug根本数据MP工具@SpringBootTestclass SpringbootDemo2MybatisApplicationTests { @Autowired private UserDao userDao; @Test public void testFind(){ List<User> userList = userDao.findAll(); System.out.println(userList); } @Test public void testSelect01(){ List<User> userList = userDao.selectList(null); System.out.println(userList); } /** * 业务: 查问id=11的用户信息 主键... */ @Test public void testSelect02(){ User user = userDao.selectById(11); System.out.println(user); } /** * 业务: 查问name属性为"小乔"的数据 * sql: select * from user where name="小乔"; * 对象的形式 > sql形式 */ @Test public void testSelect03(){ //条件结构器 QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("name", "小乔"); List<User> userList = userDao.selectList(queryWrapper); System.out.println(userList); } /** * 业务: 查问name属性为"小乔"的数据 并且 age >=18岁 * sql: select * from user where name="小乔" and age>=18; * * 大于 > gt| 小于 < lt | * 大于等于 >= ge | 小于等于 le */ @Test public void testSelect04(){ //条件结构器 QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("name", "小乔") .ge("age", 18); List<User> userList = userDao.selectList(queryWrapper); System.out.println(userList); } /** * 业务: 查问name中蕴含 "精"的用户,并且sex为女 * 业务: 查问name中蕴含 以精结尾的数据,并且sex为女 * sql: select * from user where name like "%精%" and sex="女"; */ @Test public void testSelect05(){ //条件结构器 QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.likeLeft("name", "精") .eq("sex", "女"); List<User> userList = userDao.selectList(queryWrapper); System.out.println(userList); } /** * 需要: 查问user表中的数据 要求依照年龄降序排列,如果年龄雷同依照id降序排列 */ @Test public void testSelect06(){ QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.orderByDesc("age","id"); List<User> userList = userDao.selectList(queryWrapper); System.out.println(userList); } /** * 需要: 查问name属性为null的数据. * where name is null */ @Test public void testSelect07(){ QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.isNull("name"); List<User> userList = userDao.selectList(queryWrapper); System.out.println(userList); } /** * 查问name="小乔" age=17 性别=女的用户 * 如果传递的是对象.会依据对象中不为null的属性充当where条件. */ @Test public void testSelect08(){ User user = new User(); user.setName("小乔").setAge(17).setSex("女"); QueryWrapper<User> queryWrapper = new QueryWrapper<>(user); List<User> userList = userDao.selectList(queryWrapper); System.out.println(userList); } /** * 查问id=1,3,5,10数据. * sql: select * from user where id in (1,3,5,10) */ @Test public void testSelect09(){ //转化时,留神应用对象的类型 Integer[] ids = {1,3,5,10}; List<Integer> idList = Arrays.asList(ids); List<User> userList = userDao.selectBatchIds(idList); System.out.println(userList); } @Test public void testInsert(){ User user = new User(); user.setName("特朗普").setAge(70).setSex("男"); userDao.insert(user); } /** * 删除name=null的数据,或者name="特朗普" */ @Test public void testDelete(){ QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.isNull("name") .or() .eq("name", "特朗普"); userDao.delete(queryWrapper); } /** * 案例1: 将id=1的数据的年龄改为8000岁. * sql1: update user set age=8000 where id=1; * 案例2: 要求将name="黑熊精" age=5500. * sql2: update user set age=5500 where name="黑熊精"; */ @Test public void testUpdate(){ User user = new User(); user.setId(1); //主键充当where条件 user.setAge(8000); userDao.updateById(user); //参数阐明 1.实体对象 封装set条件的值 // 2.更新条件结构器 User temp = new User(); temp.setAge(5500); UpdateWrapper<User> updateWrapper = new UpdateWrapper<>(); updateWrapper.eq("name", "黑熊精"); userDao.update(temp,updateWrapper); }

October 23, 2020 · 3 min · jiezi

关于springboot:01第四阶段

#第一份配置文件,用来指定默认的环境标识spring: profiles: active: prod---# YML文件语法 # 1. key:(空格) value # 2. key与key之间有层级的缩进关系.#指定环境的名称spring: profiles: devserver: port: 8090# 属性赋值操作,编辑属性时留神前缀. 只有springboot启动该数据就会被写入内存中 key-value格局redis: host: 192.168.126.129 port: 6379# 1.须要将环境一分为二---spring: profiles: prodserver: port: 9000# 属性赋值操作,编辑属性时留神前缀. 只有springboot启动该数据就会被写入内存中 key-value格局redis: host: 111.111.111.111 port: 7000属性赋值操作# pro文件语法 1 key=value 2.不要增加多余的""号 3.key次要不要反复. 如果一旦key反复,则以yml文件为主.pro.redis.host=111.111.111.111pro.redis.port=6379//动静获取ip和端口数据//@ResponseBody 作用1: 将对象转化为JSON 作用2: 如果返回值是String类型,则返回字符串自身// 作用3: 个别客户端发动ajax申请时,采纳该注解返回数据, 将不会执行视图解析器操作@RestController//动静的导入pro配置文件,交给spring容器进行加载.@PropertySource("classpath:/properties/redis.properties")public class RedisController { @Value("${redis.host}") //spel表达式 private String host; // = "192.168.126.130"; private String host; // = "192.168.126.130"; @Value("${redis.port}") private Integer port; // = 6379; @Value("${pro.redis.host}") private String proHost; @Value("${pro.redis.port}") private Integer proPort; //指定properties文件进行赋值操作. @RequestMapping("/getMsg") public String getMsg(){ //从yml配置文件中动静获取 return host + ":" + port; } @RequestMapping("/getPro") public String getPro(){ User user = new User(); user.setId(100).setName("AAAAA"); return proHost + ":" + proPort; }}pom依赖 不晓得当前有没有用途?<?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.com.jt.jt</groupId> <artifactId>springboot_demo2</artifactId> <version>1.0-SNAPSHOT</version> <!--1.对立定义父级我的项目--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <java.version>1.8</java.version> <!--跳过测试类加载--> <skipTests>true</skipTests> </properties> <!--2.引入第三方依赖--> <dependencies> <!--间接的依赖项--> <dependency> <groupId>org.springframework.boot</groupId> <!--springBoot启动项 外部的jar包文件曾经将配置筹备实现,用户 只须要导入jar包就能够获取其性能. starter-web 间接引入了SpringMVC框架 传统mvc框架配置: 1.导入特定的jar包及版本. 2.编辑web.xml配置 dispatcherServler 拦挡门路 3.配置mvc的配置文件 包扫描 视图解析器.... --> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <!--引入测试类的启动项 能够在测试类中间接引入容器对象--> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <!--引入插件lombok 主动的set/get/构造方法插件 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> <!--3.增加插件--> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>

October 23, 2020 · 1 min · jiezi

关于springboot:第九阶段-第一模块

October 22, 2020 · 0 min · jiezi

关于springboot:springboot之核心原理二

1.基于你对springboot的了解形容一下什么是springboot它是一个服务于spring框架的框架,可能简化配置文件,疾速构建web利用,内置tomcat,无需打包部署,间接运行。 2.约定优于配置指的是什么?maven 的目录构造a). 默认有 resources 文件夹寄存配置文件b). 默认打包形式为: jarspring-boot-starter-web 中默认蕴含 spring mvc 相干依赖以及内置的 tomcat 容器,使得构建一个 web 利用更加简略默认提供 application.properties/yml 文件默认通过 spring.profiles.active 属性来决定运行环境时读取的配置文件EnableAutoConfiguration 默认对于依赖的 starter 进行主动 3.@SpringBootApplication由哪几个注解组成,这几个注解别离示意什么作用SpringBootApplication 实质上是由 3 个注解组成,别离是 @Configuration@EnableAutoConfiguration@ComponentScan@Configuration:在启动类外面标注了@Configuration,意味着它其实也是一个 IoC容器的配置类 @EnableAutoConfiguration:springboot 利用把所有符合条件的@Configuration 配置都加载到以后 SpringBoot 创立并应用的 IoC 容器中。 @ComponentScan:ComponentScan 默认会扫描以后 package 下的的所有加了@Component 、@Repository、@Service、@Controller的类到 IoC 容器中; 4.springboot主动拆卸的实现原理如果是之前的spring中应用redis须要在xml定义bean,当初只须要依赖一个spring-boot-starter-data-redis的jar包,jar中定义了RedisConfiguration,当启动的时候spring会主动装载RedisConfiguration,那spring是如何晓得配置类在哪里的呢?RedisConfiguration类的门路放在了classpath*META-INF/spring.factories的文件中,spring会加载这个文件中配置的configuration (1)SpringApplication.run(AppConfig.class,args);执行流程中有refreshContext(context);(2)refreshContext(context);外部会解析咱们的配置类上的标签.实现主动拆卸性能的注解@EnableAutoConfiguration(3)会解析@EnableAutoConfiguration这个注解外面的@Import引入的配置类.AutoConfigurationImportSelector(4)AutoConfigurationImportSelector这个类中有这个办法. SpringFactoriesLoader.(5)SpringFactoriesLoader.loadFactoryNames的作用就是读取jar包中的/我的项目中的META-INF/spring.factories文件.(6)spring.factories配置了要主动拆卸的Configuration类 5.spring中的spi机制的原理是什么?SPI的全名为Service Provider Interface,为某个接口寻找服务实现的机制。当服务的提供者,提供了服务接口的一种实现之后,在jar包的META-INF/services/目录里同时创立一个以服务接口命名的文件。该文件里就是实现该服务接口的具体实现类。而当内部程序拆卸这个模块的时候,就能通过该jar包META-INF/services/里的配置文件找到具体的实现类名,并装载实例化,实现模块的注入。通过这个约定,就不须要把服务放在代码中了,通过模块被拆卸的时候就能够发现服务类了。 在springboot的主动拆卸过程中,最终会加载META-INF/spring.factories文件,而加载的过程是由SpringFactoriesLoader加载的。从CLASSPATH下的每个Jar包中搜查所有META-INF/spring.factories配置文件,而后将解析properties文件,找到指定名称的配置后返回。须要留神的是,其实这里不仅仅是会去ClassPath门路下查找,会扫描所有门路下的Jar包,只不过这个文件只会在Classpath下的jar包中。 通过spi技术能够自定义starter,在自定义的配置文件META-INF/spring.factories中退出实现类,依赖这个starter的我的项目就会扫描jar包下的配置,找到实现类进行装载实例化

October 22, 2020 · 1 min · jiezi

关于springboot:SpringBoot-Admin-钉钉预警

前言???????????? 本次分享 SpringBoot Admin - 应用程序监控预警(钉钉机器人)概述生产环境中微服务利用集群服务数量较大,为更快,更准确的在第一工夫监控到服务衰弱状态。应用SpringBoot Admin提供的监控告警性能实现钉钉机器人预警告诉。在Springboot Admin中内置多种开箱即用的监控告警零碎告诉,例如Mail、Slack、Telegram、Hipchat等多种告诉渠道。思考到它所反对的大多是一些国外的支流工具,而目前理论工作场景中大多应用钉钉办公,故本次分享钉钉机器人预警告诉。疾速开始创立钉钉机器人创立自定义机器人 - 复制 WebHook - token,实现创立 编码-自定义音讯告诉 编码 - 钉钉告诉 public class DingDingNotifier extends AbstractStatusChangeNotifier { public DingDingNotifier(InstanceRepository repository) { super(repository); } @Override protected Mono<Void> doNotify(InstanceEvent event, Instance instance) { String serviceName = instance.getRegistration().getName(); String serviceUrl = instance.getRegistration().getServiceUrl(); String status = instance.getStatusInfo().getStatus(); Map<String, Object> details = instance.getStatusInfo().getDetails(); StringBuilder str = new StringBuilder(); str.append("监控报警 : 【" + serviceName + "】"); str.append("【服务地址】" + serviceUrl); str.append("【状态】" + status); str.append("【详情】" + JSONObject.toJSONString(details)); return Mono.fromRunnable(() -> { DingDingMessageUtil.sendTextMessage(str.toString()); }); }}编码 - 钉钉音讯 ...

October 22, 2020 · 2 min · jiezi

关于springboot:SpringBoot-Admin-使用指南

前言???????????? 本次分享 SpringBoot Admin - SpringBoot应用程序的治理和监控。简介 SpringBoot Admin 是一个开源社区我的项目,用于治理和监控SpringBoot应用程序的运行状态。应用程序作为SpringBoot Admin Client向SpringBoot Admin Server注册(通过HTTP)或应用SpringCloud注册核心(例如Eureka、Consul、Nacos)发现,收集各个SpringBoot Admin Client Actuator接口信息进行UI丑化封装的可视化WEB监控工具。 SpringBoot Actuator 是SpringBoot的一个附加性能,SpringBoot Actuator提供了对单个SpringBoot利用的监控和治理,信息蕴含:利用状态、内存、线程、堆栈等等,比拟全面的监控了Spring Boot利用的整个生命周期。疾速开始SpringBoot Admin Server创立 SpringBoot 应用程序Maven依赖 <!-- discovery --><dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos- discovery</artifactId></dependency><!-- admin-server --><dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-starter-server</artifactId> <version>2.2.1</version></dependency>增加@EnableAdminServer注解 @EnableAdminServer@EnableDiscoveryClient@SpringBootApplicationpublic class AdminApplication { public static void main(String[] args) { SpringApplication.run(AdminApplication.class, args); }}application.yml配置 server: port: 1112spring: application: name: space-admin cloud: # 应用Nacos服务发现 nacos: discovery: server-addr: xxxx namespace: NAMESPACE group: DEFAULT_GROUP启动验证 ...

October 22, 2020 · 1 min · jiezi

关于springboot:15基于SpringMyBatisSpringBootVue技术实现购物券系统的增删改查操作

业务形容基于Spring,MyBatis,SpringBoot,VUE技术实现购物券的增删改查操作。 我的项目环境初始化筹备工作1. MySQL(5.7)2. JDK (1.8)3. Maven (3.6.3)4. IDEA(2020.2)数据库初始化关上mysql控制台,而后按如下步骤执行dbretail.sql文件。第一步:登录mysql。 mysql –uroot –proot第二步:设置控制台编码方式。 set names utf8;第三步:执行dbretail.sql文件(切记不要关上文件复制到mysql客户端运行)。 source d:/dbretail.sql其中dbvoucher.sql文件内容如下: drop database if exists dbretail;create database dbretail default character set utf8;use dbretail;CREATE TABLE tb_voucher( `id` INT UNSIGNED PRIMARY KEY AUTO_INCREMENT COMMENT '主键', `deno` DECIMAL(10,2) UNSIGNED NOT NULL COMMENT '面值', `requirement` DECIMAL(10,2) UNSIGNED NOT NULL COMMENT '订单多少钱能够应用', `startTime` DATETIME COMMENT '起始日期', `endTime` DATETIME COMMENT '截至日期', `maxNum` INT COMMENT '代金卷发放最大数量', `remark` varchar(200) COMMENT '备注', `createdTime` DATETIME COMMENT '创立日期') COMMENT='购物券表';insert into tb_voucher values (null,100,1000,'2020/05/07','2020/06/07',200,'Remark',now());insert into tb_voucher values (null,80,800,'2020/05/07','2020/06/07',300,'Remark',now());insert into tb_voucher values (null,50,500,'2020/05/07','2020/06/07',400,'Remark',now());insert into tb_voucher values (null,30,300,'2020/05/07','2020/06/07',500,'Remark',now());insert into tb_voucher values (null,10,100,'2020/05/07','2020/06/07',600,'Remark',now());创立我的项目并增加依赖基于IDEA创立第一步:创立Empty我的项目并设置根本信息(如果Empty我的项目曾经存在则无需创立) ...

October 22, 2020 · 6 min · jiezi

关于springboot:13SpringBoot工程下活动Activity模块设计及实现

业务形容基于Spring,MyBatis,SpringBoot,Thymeleaf,Ajax技术实现流动模块的查问,增加等操作。 我的项目环境初始化筹备工作1. MySQL(5.7)2. JDK (1.8)3. Maven (3.6.3)4. STS(4.7.1)数据库初始化关上mysql控制台,而后按如下步骤执行goods.sql文件。第一步:登录mysql。 mysql –uroot –proot第二步:设置控制台编码方式。 set names utf8;第三步:执行activity.sql文件(切记不要关上文件复制到mysql客户端运行)。 source d:/activity.sql其中activity.sql文件内容如下: drop database if exists dbactivity;create database dbactivity default character set utf8;use dbactivity;create table tb_activity( id bigint primary key auto_increment, title varchar(100) not null, category varchar(100) not null, startTime datetime not null, endTime datetime not null, remark text, state tinyint, createdTime datetime not null, createdUser varchar(100))engine=InnoDB;insert into tb_activity values (null,'ABS','cuoxiao','2020-02-02 15:00:00','2020-02-03 15:00:00','...',1,now(),'xiaoli');insert into tb_activity values (null,'VALIDATE','cuoxiao','2020-02-02 15:00:00','2020-02-03 15:00:00','...',1,now(),'xiaoli');insert into tb_activity values (null,'VALIDATE','cuoxiao','2020-02-02 15:00:00','2020-02-03 15:00:00','...',1,now(),'xiaoli');insert into tb_activity values (null,'ABS','cuoxiao','2020-02-02 15:00:00','2020-02-03 15:00:00','...',1,now(),'xiaoli');insert into tb_activity values (null,'ACCESS','cuoxiao','2020-02-02 15:00:00','2020-02-03 15:00:00','...',1,now(),'xiaoli');创立我的项目并增加依赖第一步:基于start.spring.io 创立我的项目并设置根本信息。 ...

October 22, 2020 · 3 min · jiezi

关于springboot:03基于IDEA创建SpringBoot项目并进行入门分析

SpringBoot 我的项目创立创立Module基于IDEA创立我的项目Module,模块名为04-springboot-start,组id和包名为com.cy,如图所示:填写module信息,如图所示:抉择我的项目module版本,临时不须要本人手动增加任何依赖,如图所示:填写Module名称,实现module创立,如图所示 我的项目构造剖析我的项目Module创立好当前,其代码构造剖析,如图所示: SpringBoot 我的项目启动剖析启动入口SpringBoot 工程中由SpringBootApplication注解形容的类为启动入口类,例如: package com.cy;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class Application {//Application.class public static void main(String[] args) {//Main Thread SpringApplication.run(Application.class, args); }}启动过程概要剖析SpringBoot工程启动时其繁难初始化过程,如图所示: 在启动过程中底层做了哪些事件,大抵形容如下:1)基于配置加载类(通过ClassLoader将指定地位的类读到内存->底层通过线程调用IO从磁盘读取到内存)。2)对类进行剖析(创立字节码对象-Class类型,通过反射获取器配置信息)。3)对于指定配置(例如由spring特定注解形容)的对象存储其配置信息(借助BeanDefinition对象存储)。4)基于BeanDefinition对象中class的配置构建类的实例(Bean对象),从进行bean对象的治理。 SpringBoot 疾速入门剖析业务形容在我的项目Module中定义一个类,类名为DefaultCache,而后将此类对象交给Spring创立并治理。最初通过单元测试对类的实例进行剖析。 API设计剖析基于业务形容,进行API及关系设计,如图所示: 代码编写及运行基于业务及API设计,进行代码编写,其过程如下: 第一步:定义DefaultCache类 package com.cy.pj.common.cache;import org.springframework.stereotype.Component;/** * @Component 注解形容的类,示意此类交给Spring框架治理。 */@Componentpublic class DefaultCache {}第二步:定义DefaultCacheTests单元测试类 package com.cy.pj.common.cache;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;public class DefaultCacheTests { /** * @Autowired 注解形容的属性由spring框架依照肯定规定为其注入值(赋值) * 赋值过程是怎么的? * 1)依赖查找?(请问查找规定是什么?) * 2)依赖注入?(须要借助什么技术?) */ @Autowired private DefaultCache defaultCache; @Test void testDefaultCache(){ System.out.println(defaultCache.toString()); //FAQ? defaultCache变量援用的对象是由谁创立的,存储到了哪里?bean pool }}第三步:运行单元测试类进行利用剖析启动运行单元测试办法,检测其输入后果,基于后果剖析:1)SpringBoot我的项目中Bean对象的构建。2)SpringBoot我的项目中Bean对象的获取。 ...

October 22, 2020 · 1 min · jiezi

关于springboot:IDEA中项目导入以及项目的环境切换

IDEA我的项目导入1.找到本人的工作空间门路,并关上目录2.将要导入IDEA的我的项目移至工作空间目录中3.关上导入的我的项目找到pom文件右键将maven增加更新一下即可 我的项目的环境切换业务阐明:因为开发时都是连贯公司本人的数据库/服务器等.把这个环境称之为"开发环境."当开发实现之后须要进行上线部署,则须要连贯"生产环境"如果频繁的切换环境,则会呈现我的项目因为批改谬误而导致问题的产生.我的项目优化: 是否提供一种策略.简化上述操作的开发过程. #spring-profiles-active示意指定默认环境;active前面写环境名,应用哪个环境就写哪个环境的名字,这里写的prod示意应用的是prod环境。~~~~spring: profiles: active: prod---#spring-profiles示意给环境一个具体的环境名字spring: profiles:devserver: port: 8090 #属性赋值操作,编辑属性时留神前缀,只有springboot启动,该数据就会被写入内存中,key-value格局redis: host: 192.168.126.130 port: 6379#---分割线,示意建设多个环境,将环境一分为二---spring: profiles: prodserver: port: 9000 #属性赋值操作,编辑属性时留神前缀,只有springboot启动,该数据就会被写入内存中,key-value格局redis: host: 111.111.111.111 port: 7000

October 21, 2020 · 1 min · jiezi

关于springboot:SpringBoot启动原理

阐明1.SpringBoot启动是如何流转的.2.什么叫做开箱即用,springBoot中如何实现开箱即用的. "开箱即用"阐明如果须要引入第三方的"工具/性能",只须要通过大量的配置/或者不做任何配置.则就能够应用该性能. 对于启动项的阐明 <!--间接的依赖项--> <dependency> <groupId>org.springframework.boot</groupId> <!--springBoot启动项 外部的jar包文件曾经将配置筹备实现,用户 只须要导入jar包就能够获取其性能. starter-web 间接引入了SpringMVC框架 传统mvc框架配置: 1.导入特定的jar包及版本. 2.编辑web.xml配置 dispatcherServler 拦挡门路 3.配置mvc的配置文件 包扫描 视图解析器.... --> <artifactId>spring-boot-starter-web</artifactId> </dependency>SpringBoot程序启动加载过程 元注解阐明:@Target(ElementType.TYPE) 对哪个元素无效 对类无效@Retention(RetentionPolicy.RUNTIME) 什么时候起作用 运行期无效@Documented 是否反对生成文档@Inherited 该注解是否能够被继承. SpringBootConfiguration阐明作用:标识主启动类是一个大型的配置文件,启动时会加载所有的小的配置文件. @Configuration: 示意该类是一个配置类. @Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Configurationpublic @interface SpringBootConfiguration {.....}excludeFilters 阐明阐明: 在springboot容器启动时,不须要加载某些过滤器.因为parent标签中定义了所有的关联的jar包文件信息.则启动时有可能导致意外的产生,所有须要提前剔除. @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })@AutoConfigurationPackage阐明: 当程序启动时,会依据主启动类的包门路,扫描其子孙包,所以springboot当前写代码时应该在其子孙包下编辑. AutoConfigurationImportSelector阐明:该配置中外部集成了所有的SpringBoot中的选择器.这些选择器的次要的工作就是查看是否有本人选择器所治理的启动项的配置. 如果发现该启动项,那么选择器就会执行该启动项,从而实现了开箱即用的操作. ============================CONDITIONS EVALUATION REPORT============================Positive matches:----------------- AopAutoConfiguration matched: - @ConditionalOnProperty (spring.aop.auto=true) matched (OnPropertyCondition) AopAutoConfiguration.ClassProxyingConfiguration matched: - @ConditionalOnMissingClass did not find unwanted class 'org.aspectj.weaver.Advice' (OnClassCondition) - @ConditionalOnProperty (spring.aop.proxy-target-class=true) matched (OnPropertyCondition) DispatcherServletAutoConfiguration matched: - @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet' (OnClassCondition) - found 'session' scope (OnWebApplicationCondition) DispatcherServletAutoConfiguration.DispatcherServletConfiguration matched: - @ConditionalOnClass found required class 'javax.servlet.ServletRegistration' (OnClassCondition) - Default DispatcherServlet did not find dispatcher servlet beans (DispatcherServletAutoConfiguration.DefaultDispatcherServletCondition) DispatcherServletAutoConfiguration.DispatcherServletRegistrationConfiguration matched: - @ConditionalOnClass found required class 'javax.servlet.ServletRegistration' (OnClassCondition) - DispatcherServlet Registration did not find servlet registration bean (DispatcherServletAutoConfiguration.DispatcherServletRegistrationCondition) DispatcherServletAutoConfiguration.DispatcherServletRegistrationConfiguration#dispatcherServletRegistration matched: - @ConditionalOnBean (names: dispatcherServlet types: org.springframework.web.servlet.DispatcherServlet; SearchStrategy: all) found bean 'dispatcherServlet' (OnBeanCondition) EmbeddedWebServerFactoryCustomizerAutoConfiguration matched: - @ConditionalOnWebApplication (required) found 'session' scope (OnWebApplicationCondition) EmbeddedWebServerFactoryCustomizerAutoConfiguration.TomcatWebServerFactoryCustomizerConfiguration matched: - @ConditionalOnClass found required classes 'org.apache.catalina.startup.Tomcat', 'org.apache.coyote.UpgradeProtocol' (OnClassCondition) ErrorMvcAutoConfiguration matched: - @ConditionalOnClass found required classes 'javax.servlet.Servlet', 'org.springframework.web.servlet.DispatcherServlet' (OnClassCondition) - found 'session' scope (OnWebApplicationCondition) ErrorMvcAutoConfiguration#basicErrorController matched: - @ConditionalOnMissingBean (types: org.springframework.boot.web.servlet.error.ErrorController; SearchStrategy: current) did not find any beans (OnBeanCondition) ErrorMvcAutoConfiguration#errorAttributes matched: - @ConditionalOnMissingBean (types: org.springframework.boot.web.servlet.error.ErrorAttributes; SearchStrategy: current) did not find any beans (OnBeanCondition) ErrorMvcAutoConfiguration.DefaultErrorViewResolverConfiguration#conventionErrorViewResolver matched: - @ConditionalOnBean (types: org.springframework.web.servlet.DispatcherServlet; SearchStrategy: all) found bean 'dispatcherServlet'; @ConditionalOnMissingBean (types: org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver; SearchStrategy: all) did not find any beans (OnBeanCondition) ErrorMvcAutoConfiguration.WhitelabelErrorViewConfiguration matched: - @ConditionalOnProperty (server.error.whitelabel.enabled) matched (OnPropertyCondition) - ErrorTemplate Missing did not find error template view (ErrorMvcAutoConfiguration.ErrorTemplateMissingCondition) ErrorMvcAutoConfiguration.WhitelabelErrorViewConfiguration#beanNameViewResolver matched: - @ConditionalOnMissingBean (types: org.springframework.web.servlet.view.BeanNameViewResolver; SearchStrategy: all) did not find any beans (OnBeanCondition) ErrorMvcAutoConfiguration.WhitelabelErrorViewConfiguration#defaultErrorView matched: - @ConditionalOnMissingBean (names: error; SearchStrategy: all) did not find any beans (OnBeanCondition) GenericCacheConfiguration matched: - Cache org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration automatic cache type (CacheCondition) HttpEncodingAutoConfiguration matched: - @ConditionalOnClass found required class 'org.springframework.web.filter.CharacterEncodingFilter' (OnClassCondition) - found 'session' scope (OnWebApplicationCondition) - @ConditionalOnProperty (server.servlet.encoding.enabled) matched (OnPropertyCondition) HttpEncodingAutoConfiguration#characterEncodingFilter matched: - @ConditionalOnMissingBean (types: org.springframework.web.filter.CharacterEncodingFilter; SearchStrategy: all) did not find any beans (OnBeanCondition) HttpMessageConvertersAutoConfiguration matched: - @ConditionalOnClass found required class 'org.springframework.http.converter.HttpMessageConverter' (OnClassCondition) - NoneNestedConditions 0 matched 1 did not; NestedCondition on HttpMessageConvertersAutoConfiguration.NotReactiveWebApplicationCondition.ReactiveWebApplication did not find reactive web application classes (HttpMessageConvertersAutoConfiguration.NotReactiveWebApplicationCondition) HttpMessageConvertersAutoConfiguration#messageConverters matched: - @ConditionalOnMissingBean (types: org.springframework.boot.autoconfigure.http.HttpMessageConverters; SearchStrategy: all) did not find any beans (OnBeanCondition) HttpMessageConvertersAutoConfiguration.StringHttpMessageConverterConfiguration matched: - @ConditionalOnClass found required class 'org.springframework.http.converter.StringHttpMessageConverter' (OnClassCondition) HttpMessageConvertersAutoConfiguration.StringHttpMessageConverterConfiguration#stringHttpMessageConverter matched: - @ConditionalOnMissingBean (types: org.springframework.http.converter.StringHttpMessageConverter; SearchStrategy: all) did not find any beans (OnBeanCondition) JacksonAutoConfiguration matched: - @ConditionalOnClass found required class 'com.fasterxml.jackson.databind.ObjectMapper' (OnClassCondition) JacksonAutoConfiguration.Jackson2ObjectMapperBuilderCustomizerConfiguration matched: - @ConditionalOnClass found required class 'org.springframework.http.converter.json.Jackson2ObjectMapperBuilder' (OnClassCondition) JacksonAutoConfiguration.JacksonObjectMapperBuilderConfiguration matched: - @ConditionalOnClass found required class 'org.springframework.http.converter.json.Jackson2ObjectMapperBuilder' (OnClassCondition) JacksonAutoConfiguration.JacksonObjectMapperBuilderConfiguration#jacksonObjectMapperBuilder matched: - @ConditionalOnMissingBean (types: org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; SearchStrategy: all) did not find any beans (OnBeanCondition) JacksonAutoConfiguration.JacksonObjectMapperConfiguration matched: - @ConditionalOnClass found required class 'org.springframework.http.converter.json.Jackson2ObjectMapperBuilder' (OnClassCondition) JacksonAutoConfiguration.JacksonObjectMapperConfiguration#jacksonObjectMapper matched: - @ConditionalOnMissingBean (types: com.fasterxml.jackson.databind.ObjectMapper; SearchStrategy: all) did not find any beans (OnBeanCondition) JacksonAutoConfiguration.ParameterNamesModuleConfiguration matched: - @ConditionalOnClass found required class 'com.fasterxml.jackson.module.paramnames.ParameterNamesModule' (OnClassCondition) JacksonAutoConfiguration.ParameterNamesModuleConfiguration#parameterNamesModule matched: - @ConditionalOnMissingBean (types: com.fasterxml.jackson.module.paramnames.ParameterNamesModule; SearchStrategy: all) did not find any beans (OnBeanCondition) JacksonHttpMessageConvertersConfiguration.MappingJackson2HttpMessageConverterConfiguration matched: - @ConditionalOnClass found required class 'com.fasterxml.jackson.databind.ObjectMapper' (OnClassCondition) - @ConditionalOnProperty (spring.mvc.converters.preferred-json-mapper=jackson) matched (OnPropertyCondition) - @ConditionalOnBean (types: com.fasterxml.jackson.databind.ObjectMapper; SearchStrategy: all) found bean 'jacksonObjectMapper' (OnBeanCondition) JacksonHttpMessageConvertersConfiguration.MappingJackson2HttpMessageConverterConfiguration#mappingJackson2HttpMessageConverter matched: - @ConditionalOnMissingBean (types: org.springframework.http.converter.json.MappingJackson2HttpMessageConverter ignored: org.springframework.hateoas.server.mvc.TypeConstrainedMappingJackson2HttpMessageConverter,org.springframework.data.rest.webmvc.alps.AlpsJsonHttpMessageConverter; SearchStrategy: all) did not find any beans (OnBeanCondition) LifecycleAutoConfiguration#defaultLifecycleProcessor matched: - @ConditionalOnMissingBean (names: lifecycleProcessor; SearchStrategy: current) did not find any beans (OnBeanCondition) MultipartAutoConfiguration matched: - @ConditionalOnClass found required classes 'javax.servlet.Servlet', 'org.springframework.web.multipart.support.StandardServletMultipartResolver', 'javax.servlet.MultipartConfigElement' (OnClassCondition) - found 'session' scope (OnWebApplicationCondition) - @ConditionalOnProperty (spring.servlet.multipart.enabled) matched (OnPropertyCondition) MultipartAutoConfiguration#multipartConfigElement matched: - @ConditionalOnMissingBean (types: javax.servlet.MultipartConfigElement,org.springframework.web.multipart.commons.CommonsMultipartResolver; SearchStrategy: all) did not find any beans (OnBeanCondition) MultipartAutoConfiguration#multipartResolver matched: - @ConditionalOnMissingBean (types: org.springframework.web.multipart.MultipartResolver; SearchStrategy: all) did not find any beans (OnBeanCondition) NoOpCacheConfiguration matched: - Cache org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration automatic cache type (CacheCondition) PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer matched: - @ConditionalOnMissingBean (types: org.springframework.context.support.PropertySourcesPlaceholderConfigurer; SearchStrategy: current) did not find any beans (OnBeanCondition) RestTemplateAutoConfiguration matched: - @ConditionalOnClass found required class 'org.springframework.web.client.RestTemplate' (OnClassCondition) - NoneNestedConditions 0 matched 1 did not; NestedCondition on RestTemplateAutoConfiguration.NotReactiveWebApplicationCondition.ReactiveWebApplication did not find reactive web application classes (RestTemplateAutoConfiguration.NotReactiveWebApplicationCondition) RestTemplateAutoConfiguration#restTemplateBuilder matched: - @ConditionalOnMissingBean (types: org.springframework.boot.web.client.RestTemplateBuilder; SearchStrategy: all) did not find any beans (OnBeanCondition) ServletWebServerFactoryAutoConfiguration matched: - @ConditionalOnClass found required class 'javax.servlet.ServletRequest' (OnClassCondition) - found 'session' scope (OnWebApplicationCondition) ServletWebServerFactoryAutoConfiguration#tomcatServletWebServerFactoryCustomizer matched: - @ConditionalOnClass found required class 'org.apache.catalina.startup.Tomcat' (OnClassCondition) ServletWebServerFactoryConfiguration.EmbeddedTomcat matched: - @ConditionalOnClass found required classes 'javax.servlet.Servlet', 'org.apache.catalina.startup.Tomcat', 'org.apache.coyote.UpgradeProtocol' (OnClassCondition) - @ConditionalOnMissingBean (types: org.springframework.boot.web.servlet.server.ServletWebServerFactory; SearchStrategy: current) did not find any beans (OnBeanCondition) SimpleCacheConfiguration matched: - Cache org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration automatic cache type (CacheCondition) TaskExecutionAutoConfiguration matched: - @ConditionalOnClass found required class 'org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor' (OnClassCondition) TaskExecutionAutoConfiguration#applicationTaskExecutor matched: - @ConditionalOnMissingBean (types: java.util.concurrent.Executor; SearchStrategy: all) did not find any beans (OnBeanCondition) TaskExecutionAutoConfiguration#taskExecutorBuilder matched: - @ConditionalOnMissingBean (types: org.springframework.boot.task.TaskExecutorBuilder; SearchStrategy: all) did not find any beans (OnBeanCondition) TaskSchedulingAutoConfiguration matched: - @ConditionalOnClass found required class 'org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler' (OnClassCondition) TaskSchedulingAutoConfiguration#taskSchedulerBuilder matched: - @ConditionalOnMissingBean (types: org.springframework.boot.task.TaskSchedulerBuilder; SearchStrategy: all) did not find any beans (OnBeanCondition) WebMvcAutoConfiguration matched: - @ConditionalOnClass found required classes 'javax.servlet.Servlet', 'org.springframework.web.servlet.DispatcherServlet', 'org.springframework.web.servlet.config.annotation.WebMvcConfigurer' (OnClassCondition) - found 'session' scope (OnWebApplicationCondition) - @ConditionalOnMissingBean (types: org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; SearchStrategy: all) did not find any beans (OnBeanCondition) WebMvcAutoConfiguration#formContentFilter matched: - @ConditionalOnProperty (spring.mvc.formcontent.filter.enabled) matched (OnPropertyCondition) - @ConditionalOnMissingBean (types: org.springframework.web.filter.FormContentFilter; SearchStrategy: all) did not find any beans (OnBeanCondition) WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#defaultViewResolver matched: - @ConditionalOnMissingBean (types: org.springframework.web.servlet.view.InternalResourceViewResolver; SearchStrategy: all) did not find any beans (OnBeanCondition) WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#requestContextFilter matched: - @ConditionalOnMissingBean (types: org.springframework.web.context.request.RequestContextListener,org.springframework.web.filter.RequestContextFilter; SearchStrategy: all) did not find any beans (OnBeanCondition) WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#viewResolver matched: - @ConditionalOnBean (types: org.springframework.web.servlet.ViewResolver; SearchStrategy: all) found beans 'defaultViewResolver', 'beanNameViewResolver', 'mvcViewResolver'; @ConditionalOnMissingBean (names: viewResolver types: org.springframework.web.servlet.view.ContentNegotiatingViewResolver; SearchStrategy: all) did not find any beans (OnBeanCondition) WebSocketServletAutoConfiguration matched: - @ConditionalOnClass found required classes 'javax.servlet.Servlet', 'javax.websocket.server.ServerContainer' (OnClassCondition) - found 'session' scope (OnWebApplicationCondition) WebSocketServletAutoConfiguration.TomcatWebSocketConfiguration matched: - @ConditionalOnClass found required classes 'org.apache.catalina.startup.Tomcat', 'org.apache.tomcat.websocket.server.WsSci' (OnClassCondition) WebSocketServletAutoConfiguration.TomcatWebSocketConfiguration#websocketServletWebServerCustomizer matched: - @ConditionalOnMissingBean (names: websocketServletWebServerCustomizer; SearchStrategy: all) did not find any beans (OnBeanCondition)Negative matches:----------------- ActiveMQAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'javax.jms.ConnectionFactory' (OnClassCondition) AopAutoConfiguration.AspectJAutoProxyingConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.aspectj.weaver.Advice' (OnClassCondition) ArtemisAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'javax.jms.ConnectionFactory' (OnClassCondition) BatchAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.batch.core.launch.JobLauncher' (OnClassCondition) CacheAutoConfiguration: Did not match: - @ConditionalOnBean (types: org.springframework.cache.interceptor.CacheAspectSupport; SearchStrategy: all) did not find any beans of type org.springframework.cache.interceptor.CacheAspectSupport (OnBeanCondition) Matched: - @ConditionalOnClass found required class 'org.springframework.cache.CacheManager' (OnClassCondition) CacheAutoConfiguration.CacheManagerEntityManagerFactoryDependsOnPostProcessor: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean' (OnClassCondition) - Ancestor org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration did not match (ConditionEvaluationReport.AncestorsMatchedCondition) CaffeineCacheConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.github.benmanes.caffeine.cache.Caffeine' (OnClassCondition) CassandraAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.datastax.oss.driver.api.core.CqlSession' (OnClassCondition) CassandraDataAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.datastax.oss.driver.api.core.CqlSession' (OnClassCondition) CassandraReactiveDataAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.datastax.oss.driver.api.core.CqlSession' (OnClassCondition) CassandraReactiveRepositoriesAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.data.cassandra.ReactiveSession' (OnClassCondition) CassandraRepositoriesAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.datastax.oss.driver.api.core.CqlSession' (OnClassCondition) ClientHttpConnectorAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.web.reactive.function.client.WebClient' (OnClassCondition) CodecsAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.web.reactive.function.client.WebClient' (OnClassCondition) CouchbaseAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.couchbase.client.java.Cluster' (OnClassCondition) CouchbaseCacheConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.couchbase.client.java.Cluster' (OnClassCondition) CouchbaseDataAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.couchbase.client.java.Bucket' (OnClassCondition) CouchbaseReactiveDataAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.couchbase.client.java.Cluster' (OnClassCondition) CouchbaseReactiveRepositoriesAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.couchbase.client.java.Cluster' (OnClassCondition) CouchbaseRepositoriesAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.couchbase.client.java.Bucket' (OnClassCondition) DataSourceAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType' (OnClassCondition) DataSourceTransactionManagerAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.jdbc.core.JdbcTemplate' (OnClassCondition) DispatcherServletAutoConfiguration.DispatcherServletConfiguration#multipartResolver: Did not match: - @ConditionalOnBean (types: org.springframework.web.multipart.MultipartResolver; SearchStrategy: all) did not find any beans of type org.springframework.web.multipart.MultipartResolver (OnBeanCondition) EhCacheCacheConfiguration: Did not match: - @ConditionalOnClass did not find required class 'net.sf.ehcache.Cache' (OnClassCondition) ElasticsearchDataAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.data.elasticsearch.core.ElasticsearchTemplate' (OnClassCondition) ElasticsearchRepositoriesAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.elasticsearch.client.Client' (OnClassCondition) ElasticsearchRestClientAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.elasticsearch.client.RestClient' (OnClassCondition) EmbeddedLdapAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.unboundid.ldap.listener.InMemoryDirectoryServer' (OnClassCondition) EmbeddedMongoAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.mongodb.MongoClientSettings' (OnClassCondition) EmbeddedWebServerFactoryCustomizerAutoConfiguration.JettyWebServerFactoryCustomizerConfiguration: Did not match: - @ConditionalOnClass did not find required classes 'org.eclipse.jetty.server.Server', 'org.eclipse.jetty.util.Loader', 'org.eclipse.jetty.webapp.WebAppContext' (OnClassCondition) EmbeddedWebServerFactoryCustomizerAutoConfiguration.NettyWebServerFactoryCustomizerConfiguration: Did not match: - @ConditionalOnClass did not find required class 'reactor.netty.http.server.HttpServer' (OnClassCondition) EmbeddedWebServerFactoryCustomizerAutoConfiguration.UndertowWebServerFactoryCustomizerConfiguration: Did not match: - @ConditionalOnClass did not find required classes 'io.undertow.Undertow', 'org.xnio.SslClientAuthMode' (OnClassCondition) ErrorWebFluxAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.web.reactive.config.WebFluxConfigurer' (OnClassCondition) FlywayAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.flywaydb.core.Flyway' (OnClassCondition) FreeMarkerAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'freemarker.template.Configuration' (OnClassCondition) GroovyTemplateAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'groovy.text.markup.MarkupTemplateEngine' (OnClassCondition) GsonAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.google.gson.Gson' (OnClassCondition) GsonHttpMessageConvertersConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.google.gson.Gson' (OnClassCondition) H2ConsoleAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.h2.server.web.WebServlet' (OnClassCondition) HazelcastAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.hazelcast.core.HazelcastInstance' (OnClassCondition) HazelcastCacheConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.hazelcast.core.HazelcastInstance' (OnClassCondition) HazelcastJpaDependencyAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.hazelcast.core.HazelcastInstance' (OnClassCondition) HibernateJpaAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'javax.persistence.EntityManager' (OnClassCondition) HttpHandlerAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.web.reactive.DispatcherHandler' (OnClassCondition) HypermediaAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.hateoas.EntityModel' (OnClassCondition) InfinispanCacheConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.infinispan.spring.embedded.provider.SpringEmbeddedCacheManager' (OnClassCondition) InfluxDbAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.influxdb.InfluxDB' (OnClassCondition) IntegrationAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.integration.config.EnableIntegration' (OnClassCondition) JCacheCacheConfiguration: Did not match: - @ConditionalOnClass did not find required class 'javax.cache.Caching' (OnClassCondition) JacksonHttpMessageConvertersConfiguration.MappingJackson2XmlHttpMessageConverterConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.fasterxml.jackson.dataformat.xml.XmlMapper' (OnClassCondition) JdbcRepositoriesAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.data.jdbc.repository.config.AbstractJdbcConfiguration' (OnClassCondition) JdbcTemplateAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.jdbc.core.JdbcTemplate' (OnClassCondition) JerseyAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.glassfish.jersey.server.spring.SpringComponentProvider' (OnClassCondition) JmsAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'javax.jms.Message' (OnClassCondition) JmxAutoConfiguration: Did not match: - @ConditionalOnProperty (spring.jmx.enabled=true) did not find property 'enabled' (OnPropertyCondition) Matched: - @ConditionalOnClass found required class 'org.springframework.jmx.export.MBeanExporter' (OnClassCondition) JndiConnectionFactoryAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.jms.core.JmsTemplate' (OnClassCondition) JndiDataSourceAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType' (OnClassCondition) JooqAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.jooq.DSLContext' (OnClassCondition) JpaRepositoriesAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.data.jpa.repository.JpaRepository' (OnClassCondition) JsonbAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'javax.json.bind.Jsonb' (OnClassCondition) JsonbHttpMessageConvertersConfiguration: Did not match: - @ConditionalOnClass did not find required class 'javax.json.bind.Jsonb' (OnClassCondition) JtaAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'javax.transaction.Transaction' (OnClassCondition) KafkaAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.kafka.core.KafkaTemplate' (OnClassCondition) LdapAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.ldap.core.ContextSource' (OnClassCondition) LdapRepositoriesAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.data.ldap.repository.LdapRepository' (OnClassCondition) LiquibaseAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'liquibase.change.DatabaseChange' (OnClassCondition) MailSenderAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'javax.mail.internet.MimeMessage' (OnClassCondition) MailSenderValidatorAutoConfiguration: Did not match: - @ConditionalOnSingleCandidate did not find required type 'org.springframework.mail.javamail.JavaMailSenderImpl' (OnBeanCondition) MessageSourceAutoConfiguration: Did not match: - ResourceBundle did not find bundle with basename messages (MessageSourceAutoConfiguration.ResourceBundleCondition) MongoAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.mongodb.client.MongoClient' (OnClassCondition) MongoDataAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.mongodb.client.MongoClient' (OnClassCondition) MongoReactiveAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.mongodb.reactivestreams.client.MongoClient' (OnClassCondition) MongoReactiveDataAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.mongodb.reactivestreams.client.MongoClient' (OnClassCondition) MongoReactiveRepositoriesAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.mongodb.reactivestreams.client.MongoClient' (OnClassCondition) MongoRepositoriesAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.mongodb.client.MongoClient' (OnClassCondition) MustacheAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.samskivert.mustache.Mustache' (OnClassCondition) Neo4jDataAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.neo4j.ogm.session.SessionFactory' (OnClassCondition) Neo4jRepositoriesAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.neo4j.ogm.session.Neo4jSession' (OnClassCondition) OAuth2ClientAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.security.config.annotation.web.configuration.EnableWebSecurity' (OnClassCondition) OAuth2ResourceServerAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken' (OnClassCondition) PersistenceExceptionTranslationAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor' (OnClassCondition) ProjectInfoAutoConfiguration#buildProperties: Did not match: - @ConditionalOnResource did not find resource '${spring.info.build.location:classpath:META-INF/build-info.properties}' (OnResourceCondition) ProjectInfoAutoConfiguration#gitProperties: Did not match: - GitResource did not find git info at classpath:git.properties (ProjectInfoAutoConfiguration.GitResourceAvailableCondition) QuartzAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.quartz.Scheduler' (OnClassCondition) R2dbcAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'io.r2dbc.spi.ConnectionFactory' (OnClassCondition) R2dbcDataAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.data.r2dbc.core.DatabaseClient' (OnClassCondition) R2dbcRepositoriesAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'io.r2dbc.spi.ConnectionFactory' (OnClassCondition) R2dbcTransactionManagerAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.data.r2dbc.connectionfactory.R2dbcTransactionManager' (OnClassCondition) RSocketMessagingAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'io.rsocket.RSocketFactory' (OnClassCondition) RSocketRequesterAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'io.rsocket.RSocketFactory' (OnClassCondition) RSocketSecurityAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.security.rsocket.core.SecuritySocketAcceptorInterceptor' (OnClassCondition) RSocketServerAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'io.rsocket.core.RSocketServer' (OnClassCondition) RSocketStrategiesAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'io.netty.buffer.PooledByteBufAllocator' (OnClassCondition) RabbitAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.rabbitmq.client.Channel' (OnClassCondition) ReactiveElasticsearchRepositoriesAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.data.elasticsearch.client.reactive.ReactiveElasticsearchClient' (OnClassCondition) ReactiveElasticsearchRestClientAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'reactor.netty.http.client.HttpClient' (OnClassCondition) ReactiveOAuth2ClientAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'reactor.core.publisher.Flux' (OnClassCondition) ReactiveOAuth2ResourceServerAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity' (OnClassCondition) ReactiveSecurityAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'reactor.core.publisher.Flux' (OnClassCondition) ReactiveUserDetailsServiceAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.security.authentication.ReactiveAuthenticationManager' (OnClassCondition) ReactiveWebServerFactoryAutoConfiguration: Did not match: - @ConditionalOnWebApplication did not find reactive web application classes (OnWebApplicationCondition) RedisAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.data.redis.core.RedisOperations' (OnClassCondition) RedisCacheConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.data.redis.connection.RedisConnectionFactory' (OnClassCondition) RedisReactiveAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'reactor.core.publisher.Flux' (OnClassCondition) RedisRepositoriesAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.data.redis.repository.configuration.EnableRedisRepositories' (OnClassCondition) RepositoryRestMvcAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration' (OnClassCondition) Saml2RelyingPartyAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository' (OnClassCondition) SecurityAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.security.authentication.DefaultAuthenticationEventPublisher' (OnClassCondition) SecurityFilterAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.security.config.http.SessionCreationPolicy' (OnClassCondition) SendGridAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'com.sendgrid.SendGrid' (OnClassCondition) ServletWebServerFactoryAutoConfiguration#forwardedHeaderFilter: Did not match: - @ConditionalOnProperty (server.forward-headers-strategy=framework) did not find property 'server.forward-headers-strategy' (OnPropertyCondition) ServletWebServerFactoryConfiguration.EmbeddedJetty: Did not match: - @ConditionalOnClass did not find required classes 'org.eclipse.jetty.server.Server', 'org.eclipse.jetty.util.Loader', 'org.eclipse.jetty.webapp.WebAppContext' (OnClassCondition) ServletWebServerFactoryConfiguration.EmbeddedUndertow: Did not match: - @ConditionalOnClass did not find required classes 'io.undertow.Undertow', 'org.xnio.SslClientAuthMode' (OnClassCondition) SessionAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.session.Session' (OnClassCondition) SolrAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.apache.solr.client.solrj.impl.CloudSolrClient' (OnClassCondition) SolrRepositoriesAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.apache.solr.client.solrj.SolrClient' (OnClassCondition) SpringApplicationAdminJmxAutoConfiguration: Did not match: - @ConditionalOnProperty (spring.application.admin.enabled=true) did not find property 'enabled' (OnPropertyCondition) SpringDataWebAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.data.web.PageableHandlerMethodArgumentResolver' (OnClassCondition) TaskSchedulingAutoConfiguration#taskScheduler: Did not match: - @ConditionalOnBean (names: org.springframework.context.annotation.internalScheduledAnnotationProcessor; SearchStrategy: all) did not find any beans named org.springframework.context.annotation.internalScheduledAnnotationProcessor (OnBeanCondition) ThymeleafAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.thymeleaf.spring5.SpringTemplateEngine' (OnClassCondition) TransactionAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.transaction.PlatformTransactionManager' (OnClassCondition) UserDetailsServiceAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.security.authentication.AuthenticationManager' (OnClassCondition) ValidationAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'javax.validation.executable.ExecutableValidator' (OnClassCondition) WebClientAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.web.reactive.function.client.WebClient' (OnClassCondition) WebFluxAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.web.reactive.config.WebFluxConfigurer' (OnClassCondition) WebMvcAutoConfiguration#hiddenHttpMethodFilter: Did not match: - @ConditionalOnProperty (spring.mvc.hiddenmethod.filter.enabled) did not find property 'enabled' (OnPropertyCondition) WebMvcAutoConfiguration.ResourceChainCustomizerConfiguration: Did not match: - @ConditionalOnEnabledResourceChain did not find class org.webjars.WebJarAssetLocator (OnEnabledResourceChainCondition) WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#beanNameViewResolver: Did not match: - @ConditionalOnMissingBean (types: org.springframework.web.servlet.view.BeanNameViewResolver; SearchStrategy: all) found beans of type 'org.springframework.web.servlet.view.BeanNameViewResolver' beanNameViewResolver (OnBeanCondition) WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter#localeResolver: Did not match: - @ConditionalOnProperty (spring.mvc.locale) did not find property 'locale' (OnPropertyCondition) WebServiceTemplateAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.oxm.Marshaller' (OnClassCondition) WebServicesAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.ws.transport.http.MessageDispatcherServlet' (OnClassCondition) WebSocketMessagingAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer' (OnClassCondition) WebSocketReactiveAutoConfiguration: Did not match: - @ConditionalOnWebApplication did not find reactive web application classes (OnWebApplicationCondition) WebSocketServletAutoConfiguration.JettyWebSocketConfiguration: Did not match: - @ConditionalOnClass did not find required class 'org.eclipse.jetty.websocket.jsr356.server.deploy.WebSocketServerContainerInitializer' (OnClassCondition) WebSocketServletAutoConfiguration.UndertowWebSocketConfiguration: Did not match: - @ConditionalOnClass did not find required class 'io.undertow.websockets.jsr.Bootstrap' (OnClassCondition) XADataSourceAutoConfiguration: Did not match: - @ConditionalOnClass did not find required class 'javax.transaction.TransactionManager' (OnClassCondition)Exclusions:----------- NoneUnconditional classes:---------------------- org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration

October 20, 2020 · 13 min · jiezi

关于springboot:Spring-Cloud-Spring-Security实践一-基本概念及实践

根本应用Spring security须要的根本依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>其余局部不须要任何的减少。 Security的实践是两个外围:认证(我是谁)和鉴权(我能做什么)。 在code中,这两个外围都须要通过继承WebSecurityConfigurerAdapter来实现。 ➡️废话不多说,上代码 首先,确保yml中增加了下面提到的两个依赖。增加后这就是最根本的spring security工程了。 而后,咱们能够先增加一些controller。比方IndexController @RestControllerpublic class IndexController{ @RequestMapping(value = "/", method = RequestMethod.GET) public String index(){ return "index"; }}此时启动我的项目,会发现启动log中夹杂着一句乱码: Using generated security password: 2465a939-a37d-4d3e-9ee1-05d2e51f18fb这个“乱码”就是spring security提供的缺省明码。此时拜访我的项目url,会主动跳转到我的项目url/login页面。默认username为user, password栏输出刚刚那一句“乱码”。点击signin,发现跳转胜利,会拜访到咱们最后拜访的页面。 自定义用户名明码 - 第一种内存模式创立@configuration: 新建一个类,继承 WebSecurityConfigurerAdapter, 增加注解@EnableWebSecurity (不必再增加@Configuration注解,因为已被EnableWebSecurity蕴含)如下所示。 @EnableWebSecuritypublic class SecurityConfiguration extends WebSecurityConfigurerAdapter {}覆写父类办法: 覆写configure(AuthenticationManagerBuilder auth)办法⚠️ 父类中蕴含多个configure办法,留神抉择正确办法。代码如下所示: @Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("user").password(new BCryptPasswordEncoder().encode("123")).roles("USER");}此办法实现了三个性能: 定义了用户名和明码(user/123)加密了明码 - ⚠️ springsecurity强制明码加密,此处必须这样写定义此用户的role为USER - Spring security依据role来做鉴权操作,此处只是认证,临时漠视即可。此时,重启我的项目,曾经看不到最开始那一串乱码了,应用user/123登陆,即可跳转至正确页面。 ...

October 19, 2020 · 1 min · jiezi

关于springboot:15基于SpringMyBatisSpringBootVue技术实现购物券的增删改查操作

业务形容基于Spring,MyBatis,SpringBoot,Thymeleaf技术实现购物券的增删改查操作。 我的项目环境初始化筹备工作1. MySQL(5.7)2. JDK (1.8)3. Maven (3.6.3)4. IDEA(2020.2)数据库初始化关上mysql控制台,而后按如下步骤执行dbretail.sql文件。 第一步:登录mysql。 mysql –uroot –proot第二步:设置控制台编码方式。 set names utf8;第三步:执行dbretail.sql文件(切记不要关上文件复制到mysql客户端运行)。 source d:/dbretail.sql其中dbvoucher.sql文件内容如下: drop database if exists dbretail;create database dbretail default character set utf8;use dbretail;CREATE TABLE tb_voucher( `id` INT UNSIGNED PRIMARY KEY AUTO_INCREMENT COMMENT '主键', `deno` DECIMAL(10,2) UNSIGNED NOT NULL COMMENT '面值', `requirement` DECIMAL(10,2) UNSIGNED NOT NULL COMMENT '订单多少钱能够应用', `startTime` DATETIME COMMENT '起始日期', `endTime` DATETIME COMMENT '截至日期', `maxNum` INT COMMENT '代金卷发放最大数量', `remark` varchar(200) COMMENT '备注', `createdTime` DATETIME COMMENT '创立日期') COMMENT='购物券表';insert into tb_voucher values (null,100,1000,'2020/05/07','2020/06/07',200,'Remark',now());insert into tb_voucher values (null,80,800,'2020/05/07','2020/06/07',300,'Remark',now());insert into tb_voucher values (null,50,500,'2020/05/07','2020/06/07',400,'Remark',now());insert into tb_voucher values (null,30,300,'2020/05/07','2020/06/07',500,'Remark',now());insert into tb_voucher values (null,10,100,'2020/05/07','2020/06/07',600,'Remark',now());创立我的项目并增加依赖基于IDEA创立第一步:创立Empty我的项目并设置根本信息(如果Empty我的项目曾经存在则无需创立)第二步:基于start.spring.io 创立我的项目Module,并设置根本信息。第三步:创立我的项目module时指定我的项目外围依赖第四步:持续实现module的创立并剖析其构造 ...

October 19, 2020 · 4 min · jiezi

关于springboot:15SpringBoot工程中前段JS问题调试分析

我的项目中客户端JS常见问题 总结(Summary)本大节次要是列出了几个客户端常见问题,这些问题的解决要联合业务进行断点,日志,排除法进行剖析,而后从实际中进行进步.

October 19, 2020 · 1 min · jiezi

关于springboot:14SpringBootMybatisVue实现商品模块的crud操作

筹备工作第一步 创立新module,名字为10-springboot-goods-vue.第二步 增加maven依赖并进行初步配置(拷贝即可)第三步 拷贝pojo,dao,service包中的所有接口和类.第四步 拷贝动态资源到static目录(例如vue.js,axios.min.js) 商品查问设计及实现创立GoodsController并定义相干办法,代码如下: package com.cy.pj.goods.controller;import com.cy.pj.goods.pojo.Goods;import com.cy.pj.goods.service.GoodsService;import java.util.List;@RestControllerpublic class GoodsController { @Autowired private GoodsService goodsService; /**查问所有商品信息*/ @GetMapping("/goods/doFindGoods") public List<Goods> doFindGoods(){ return goodsService.findGoods(); }}在我的项目static目录创立goods-vue.html,并基于vue出现数据,代码如下 <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <div id="app"> <h1>The Goods Page</h1> <table> <thead> <tr> <th>id</th> <th>name</th> <th>remark</th> <th>createdTime</th> </tr> </thead> <tbody> <tr v-for="g in goods"> <td>{{g.id}}</td> <td>{{g.name}}</td> <td>{{g.remark}}</td> <td>{{g.createdTime}}</td> </tr> </tbody> </table> </div> <script src="js/axios.min.js"></script> <script src="js/vue.js"></script> <script> var vm=new Vue({//vue对象时vue.js利用的入口对象 el:"#app",//vue对象要监控的区域 data:{//此对象用于同步页面数据的一个对象 goods:{} }, methods:{//同步与页面元素事件处理函数 doFindGoods:function(){ let url="goods/doFindGoods"; axios.get(url) .then(function(result){ this.vm.goods=result.data; }); } }, mounted:function(){ this.doFindGoods(); } }); </script></body></html>启动tomcat进行拜访测试,如图所示: ...

October 19, 2020 · 1 min · jiezi

关于springboot:12SpringBoot工程中的响应标准设计及实现

背景剖析在基于C/S架构的编程模型中,客户端往往须要对服务端返回的数据,基于状态的不同进行不同的解决。例如,正确的状态数据一种出现形式,谬误的状态数据是另外一种出现形式。于是服务端响应数据的标准化设计油然而生。 响应规范设计在响应数据标准化设计时,首先要对响应数据进行剖析,哪些数据要响应到客户端,对这些数据进行怎么的状态设计等。如果当初响应的业务数据蕴含三局部:状态,音讯,具体数据。咱们能够这样设计,例如: package com.cy.pj.common.pojo;/** * 基于此对象封装服务端响应到客户端的数据 */public class ResponseResult { /**响应状态码(有的人用code)*/ private Integer state=1;//1示意ok,0示意error,..... /**状态码对应的信息*/ private String message="ok"; /**正确的响应数据*/ private Object data; public ResponseResult(){} public ResponseResult(String message){//new ResponseResult("delete ok"), this.message=message; } public ResponseResult(Object data){//new ResponseResult(list); this.data=data; } public ResponseResult(Throwable e){//new ResponseResult(e); this.state=0; this.message=e.getMessage(); } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Object getData() { return data; } public void setData(Object data) { this.data = data; }}响应数据的封装在Controller类的逻辑办法中进行失常的响应数据封装,例如: ...

October 19, 2020 · 1 min · jiezi

关于springboot:11SpringBoot工程中的异常处理方式

背景剖析在我的项目的开发中,不论是对底层的数据逻辑操作过程,还是业务逻辑的处理过程,还是管制逻辑的处理过程,都不可避免会遇到各种可预知的、不可预知的异样。解决好异样对系统有很好的爱护作用,同时会大大提高用户的体验。 异样解决剖析概述Java我的项目中解决异样形式无非两种,要么执行trycatch操作,要么执行throw操作(抛给其它对象解决),无论采纳哪种形式,其目标是让咱们的系统对异样要有反馈。但当初的问题是咱们如何让这种反馈代码的编写即简略又直观、敌对。 解决标准咱们在解决异样的过程中通常要遵循肯定的设计规范,例如: 捕捉异样时与抛出的异样必须齐全匹配,或者捕捉异样是抛出异样的父类类型。防止间接抛出RuntimeException,更不容许抛出Exception或者Throwable,应应用有业务含意的自定义异样(例如ServiceException)。捕捉异样后必须进行解决(例如记录日志)。如果不想解决它,须要将异样抛给它的调用者。最外层的逻辑必须解决异样,将其转化成用户能够了解的内容。避免出现反复的代码(Don’t Repeat Yourself),即DAY准则。SpringBoot 工程下的异样解决筹备工作第一步:创立我的项目或module,并增加web依赖,代码如下: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>第二步:批改我的项目拜访端口为80,例如 server.port=80第三步:定义Controller类,代码如下: package com.cy.pj.arithmetic.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controllerpublic class ArithmeticController { @RequestMapping("doCompute/{n1}/{n2}") @ResponseBody public String doCompute(@PathVariable Integer n1, @PathVariable Integer n2){ Integer result=n1/n2; return "Result is "+result; }}第四步启动我的项目进行拜访测试 在浏览器地址栏输出http://localhost/doCompute/10/2,检测输入后果。 Result is 5默认异样解决在浏览器地址栏输出http://localhost/doCompute/10/0,检测输入后果。对于这样的默认异样解决(spring boot提供),用户体验不太敌对,为了出现更加敌对的异样信息,咱们通常要对异样进行自定义解决。 本人try异样解决在管制层办法中,咱们能够进行try catch解决,例如: @RequestMapping("doCompute/{n1}/{n2}") @ResponseBody public String doCompute(@PathVariable Integer n1, @PathVariable Integer n2){ try{ Integer result=n1/n2; return "Result is "+result; }catch(ArithmeticException e){ return "exception is "+e.getMessage(); } } 一个Controller类中通常会有多个办法,这样多个办法中都写try语句进行异样解决会带来大量反复代码的编写,不易保护。 ...

October 19, 2020 · 1 min · jiezi

关于springboot:10SpringBoot工程的健康监控实现

衰弱监控简述Spring Boot 中actuator模块提供了健康检查,审计、指标收集,HTTP跟踪等性能,能够帮忙咱们更好的治理和跟踪springboot我的项目。 衰弱监控配置实现在须要应用衰弱监控的我的项目或module中,增加如下依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId></dependency>增加完依赖当前,reload我的项目或module。 衰弱监控启动剖析启动我的项目,在浏览器中输出如下地址:(SpringBoot默认关上的监控选项无限) http://localhost/actuator其拜访后果,如图所示:还能够在actuator列出的选中中进行点击,例如拜访health http://localhost/actuator/health其出现后果,如图所示(其中up状态示意失常):如果心愿查看更多actuator选项,能够在spring boot中配置文件 application.properties中增加如下语句: management.endpoints.web.exposure.include=***而后,重启服务器,基于拜访http://localhost/actuator地址...) 总结(Summary)本大节次要是对springboot工程中的衰弱监控性能做了一个繁难剖析和实现,本人能够基于业务的须要,进行监控的配置和剖析.

October 19, 2020 · 1 min · jiezi

关于springboot:09springboot工程中的热部署实现

热部署简介Spring Boot 开发者为Spring Boot我的项目中提供了一个热部署(spring-boot-devtools)模块,反对我的项目的热部署(批改了某些资源当前无需重启服务),以进步开发效率.其底层其实是借助了两个类加载器做了具体实现,一个类加载器加载不变class,一个类加载器加载可能变动类,以提供类的热部署性能. 热部署环境初始化本次热部署的演示在IDEA开发中进行实现,其它工具能够本人通过搜索引擎进行学习。 IDEA 启动主动编译,如图所示:IDEA工具中启动注册窗口(按ctrl+shift+alt+/),如图所示:抉择编译构建配置,如图所示: 热部署在我的项目中利用在须要热部署的我的项目或module中增加如下依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope></dependency>依赖下载当前,可重启reload我的项目,而后当咱们批改了src/main/java目录下的java文件或批改了src/main/resources目录下的配置文件时,默认都会重启你的web服务器,然而批改了测试类或html文件不会主动重启和部署。 总结(summary)本大节对springboot工程中的热部署进行了剖析和实现,能够idea工具中实际整个过程。

October 19, 2020 · 1 min · jiezi

关于springboot:05SpringBoot工程中的MyBatis框架的整合实现及原理分析

整合MyBatis的初步剖析概述Mybatis是一个优良的长久层框架,底层基于JDBC实现与数据库的交互。并在JDBC操作的根底上做了封装和优化,它借助灵便的SQL定制,参数及后果集的映射形式,更好的适应了以后互联网技术的倒退。Mybatis框架的简略利用架构如图所示:在当今的互联网利用中我的项目,mybatis框架通常会由spring框架进行资源整合,作为数据层技术实现数据交互操作。 筹备工作第一步:创立我的项目module,例如: 第二步:增加依赖 mysql 驱动依赖 <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope></dependency>spring jdbc 依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId></dependency>mybatis starter依赖 <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version></dependency> 第二步:application.properties 配置文件中增加繁难配置 连接池配置 spring.datasource.url=jdbc:mysql:///dbgoods?serverTimezone=GMT%2B8&characterEncoding=utf8spring.datasource.username=rootspring.datasource.password=rootmybatis配置 mybatis.mapper-locations=classpath:/mapper/*/*.xml环境测试代码实现在src/test/java目录中增加测试类,对mybatis框架整合进行根本测试,代码如下: package com.cy.pj.goods.dao;import java.sql.Connection;import org.apache.ibatis.session.SqlSession;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;@SpringBootTestpublic class MyBatisTests { @Autowired private SqlSession sqlSession; @Test public void testGetConnection() { Connection conn=sqlSession.getConnection(); System.out.println("connection="+conn); }}在SpringBoot脚手架工程中,Spring框架会基于MyBatis框架底层配置,创立SqlSessionFactory对象,而后再通过此工厂对象创立SqlSession,最初基于Springku框架为测试类注入SqlSession对象,接下来,咱们能够通过SqlSession对象实现与数据库的会话了。 整合MyBatis业务代码实现及原理剖析业务形容基于SpringBoot脚手架工程对MyBatis框架的整合,实现对商品库中商品数据的查问业务。 API架构设计 业务时序图剖析 业务代码设计及实现第一步:定义商品模块POJO对象类型(基于此对象存储商品数据),代码如下: package com.cy.pj.goods.pojo;import java.util.Date;/**用于存储商品信息的pojo对象*/public class Goods { private Long id; private String name; private String remark; private Date createdTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Date getCreatedTime() { return createdTime; } public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; }}第二步:定义商品模块长久层对象GoodsDao接口及办法映射,代码如下 ...

October 19, 2020 · 2 min · jiezi

关于springboot:08springboot工程下lombok的应用

背景剖析在理论的java我的项目中咱们创立的所有pojo类简直都要为属性增加set/get/toString等相干办法,所有的日志记录相干类可能都要创立日志等对象,这些样板代码既没有技术含量,又影响着代码的好看,同时反复的编码过程会在无形中加大咱们的工作量。 此时Lombok应运而生。 lombok简介概述Lombok是一个第三的Java库,它会主动插入编辑器和构建工具中,Lombok提供了一组有用的正文,用来通知编译过程中的编译工具,在源代码编译成字节码的过程中,在字节码中增加一些量样板代码。 罕用注解剖析@Setter 用于为形容的类生成setter办法,不蕴含final润饰属性。@Getter 用于为形容的类生成getter办法。@ToString 用于为形容的类增加toString办法。@EqualsAndHashCode 用于为形容的类,生成hashCode和equals办法。@NoArgsConstructor 用于为形容的类生成无参的构造方法。@AllArgsConstructor 用于为形容的类生成蕴含类中所有字段的构造方法。@Data用于为形容的类生成setter/getter、equals、canEqual、hashCode、toString办法,如为final属性,则不会为该属性生成setter办法。@Slf4J 用于为形容的类增加一个日志属性对象。lombok装置idea中的装置配置第一步:关上idea的设置窗口,找到plugins菜单,搜寻lombok进行装置,如图所示:第二步:启动注解解决,如图所示:第三步:重启idea(可选,有的idea版本须要)。 sts中的装置配置本人百度尝试。 lombok在maven我的项目中利用第一步:增加lombok依赖。 <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>annotationProcessor</scope></dependency>第二步:在类上利用lombok注解。 @Data @NoArgsConstructor @AllArgsConstructor public class Goods { private Long id; private String name; private String remark; private Date createdTime;}第三步:编写单元测试类检测Lombok注解利用 @Slf4j@SpringBootTestpublic class GoodsTests{ @Test void testGoods(){ Goods g=new Goods(); g.setId(100L); g.setName("Lombok"); log.info("id的值为{}",g.getId()); log.info("name的值为{}",g.getName()); }}总结(Summary)本大节次要对lombok做了一个剖析,装置和配置,并结合实际我的项目解说了lombok的利用场景及具体利用过程。

October 19, 2020 · 1 min · jiezi

关于springboot:06SpringBoot工程下Spring-MVC技术的应用

Spring MVC 简介背景剖析在大型软件系统设计时,业务个别会绝对简单,如果所有业务实现的代码都纠缠在一起,会呈现逻辑不清晰、可读性差,保护艰难,改变一处就牵一发而动全身等问题。为了更好解决这个问题就有了咱们当初常说的分层架构设计。 MVC 是什么MVC是一种软件架构设计思维,基于MVC架构将咱们的应用软件进行分层设计和实现,例如能够分为视图层(View),管制层(Controller),模型层(Model),通过这样的分层设计让咱们程序具备更好的灵活性和可可扩展性.因为这样能够将一个简单应用程序进行简化,实现各司其职,各尽所能.比拟适宜一个大型利用的开发. Spring MVC 概述Spring MVC是MVC设计思维在Spring框架中的一种实现,基于这样的思维spring框架设计了一些相干对象,用于更好的基于MVC架构解决申请和响应,其繁难架构如图所示: 其中:1)DispatcherServlet是客户端所有申请解决的入口,负责申请转发。2)RequestMapping负责存储申请url到后端handler对象之间的映射。3)Handler 用于解决DispatcherServlet对象转发过去的申请数据。4)ViewResolver负责解决所有Handler对象响应后果中的view。 Spring MVC 疾速入门筹备工作第一步:创立我的项目module,根本信息如图所示: 第二步:增加我的项目依赖(能够在module创立时,也能够创立后),代码如下: Spring Web 依赖(提供了spring mvc反对并且会嵌入一个tomcat) <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>Thymeleaf 依赖(提供了以html作为页面模板进行解析和操作的相干对象) <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>第三步:启动我的项目检测控制台启动状态是否OK statics 目录剖析及利用statics 目录为springboot工程创立时增加了web依赖当前主动创立的目录,此目录中能够存储html、css、js、html等相干资源,这些资源能够在启动服务器当前,间接在浏览器进行拜访。例如:第一步:在statics目录下创立一个index.html页面,代码如下: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <h1>The First Html Page</h1></body></html>第二步:启动服务器并间接进行拜访测试,如图所示 templates 目录剖析及利用templates 目录为springboot工程创立时增加了thymeleaf依赖当前主动创立的目录,此目录中要存储一些html模板,这个模板页面不能间接通过浏览器url进行拜访,须要基于后端控制器,在办法中定义页面响应,例如: 第一步:定义TemplateController及办法,代码如下: package com.cy.pj.health.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class TemplateController { @RequestMapping("doTemplateUI") public String doTemplateUI(){ return "default"; }}第二步:在templates目录中定义模板页面default.html,代码如下: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <h1>The Default Template page</h1></body></html>其中,如果default.html要在放在templates子目录中,则还须要在配置文件中配置thymeleaf的前缀,例如: ...

October 19, 2020 · 2 min · jiezi

关于springboot:06SpringBoot工程下Spring-MVC技术的应用

Spring MVC 简介背景剖析在大型软件系统设计时,业务个别会绝对简单,如果所有业务实现的代码都纠缠在一起,会呈现逻辑不清晰、可读性差,保护艰难,改变一处就牵一发而动全身等问题。为了更好解决这个问题就有了咱们当初常说的分层架构设计。 MVC 是什么MVC是一种软件架构设计思维,基于MVC架构将咱们的应用软件进行分层设计和实现,例如能够分为视图层(View),管制层(Controller),模型层(Model),通过这样的分层设计让咱们程序具备更好的灵活性和可可扩展性.因为这样能够将一个简单应用程序进行简化,实现各司其职,各尽所能.比拟适宜一个大型利用的开发. Spring MVC 概述Spring MVC是MVC设计思维在Spring框架中的一种实现,基于这样的思维spring框架设计了一些相干对象,用于更好的基于MVC架构解决申请和响应,其繁难架构如图所示:其中:1)DispatcherServlet是客户端所有申请解决的入口,负责申请转发。2)RequestMapping负责存储申请url到后端handler对象之间的映射。3)Handler 用于解决DispatcherServlet对象转发过去的申请数据。4)ViewResolver负责解决所有Handler对象响应后果中的view。 Spring MVC 疾速入门筹备工作第一步:创立我的项目module,根本信息如图所示:第二步:增加我的项目依赖(能够在module创立时,也能够创立后),代码如下: Spring Web 依赖(提供了spring mvc反对并且会嵌入一个tomcat) <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>Thymeleaf 依赖(提供了以html作为页面模板进行解析和操作的相干对象) <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>第三步:启动我的项目检测控制台启动状态是否OK statics 目录剖析及利用statics 目录为springboot工程创立时增加了web依赖当前主动创立的目录,此目录中能够存储html、css、js、html等相干资源,这些资源能够在启动服务器当前,间接在浏览器进行拜访。例如:第一步:在statics目录下创立一个index.html页面,代码如下: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <h1>The First Html Page</h1></body></html>第二步:启动服务器并间接进行拜访测试,如图所示 templates 目录剖析及利用templates 目录为springboot工程创立时增加了thymeleaf依赖当前主动创立的目录,此目录中要存储一些html模板,这个模板页面不能间接通过浏览器url进行拜访,须要基于后端控制器,在办法中定义页面响应,例如: 第一步:定义TemplateController及办法,代码如下: package com.cy.pj.health.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class TemplateController { @RequestMapping("doTemplateUI") public String doTemplateUI(){ return "default"; }}第二步:在templates目录中定义模板页面default.html,代码如下: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <h1>The Default Template page</h1></body></html>其中,如果default.html要在放在templates子目录中,则还须要在配置文件中配置thymeleaf的前缀,例如: spring.thymeleaf.prefix=classpath:/templates/module/第三步:启动服务进行拜访测试,如图所示: SpringMVC 响应数据处理ModelAndView 利用咱们有一业务,当初须要将响应数据封装到ModelAndView对象,而后响应到客户端,如何实现呢? ...

October 19, 2020 · 2 min · jiezi

关于springboot:08springboot-工程下lombok的应用

背景剖析在理论的java我的项目中咱们创立的所有pojo类简直都要为属性增加set/get/toString等相干办法,所有的日志记录相干类可能都要创立日志等对象,这些样板代码既没有技术含量,又影响着代码的好看,同时反复的编码过程会在无形中加大咱们的工作量。 此时Lombok应运而生。 lombok简介概述Lombok是一个第三的Java库,它会主动插入编辑器和构建工具中,Lombok提供了一组有用的正文,用来通知编译过程中的编译工具,在源代码编译成字节码的过程中,在字节码中增加一些量样板代码。 罕用注解剖析@Setter 用于为形容的类生成setter办法,不蕴含final润饰属性。@Getter 用于为形容的类生成getter办法。@ToString 用于为形容的类增加toString办法。@EqualsAndHashCode 用于为形容的类,生成hashCode和equals办法。@NoArgsConstructor 用于为形容的类生成无参的构造方法。@AllArgsConstructor 用于为形容的类生成蕴含类中所有字段的构造方法。@Data用于为形容的类生成setter/getter、equals、canEqual、hashCode、toString办法,如为final属性,则不会为该属性生成setter办法。@Slf4J 用于为形容的类增加一个日志属性对象。lombok装置idea中的装置配置第一步:关上idea的设置窗口,找到plugins菜单,搜寻lombok进行装置,如图所示: 第二步:启动注解解决,如图所示: 第三步:重启idea(可选,有的idea版本须要)。 sts中的装置配置本人百度尝试。 lombok在maven我的项目中利用第一步:增加lombok依赖。 <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>annotationProcessor</scope></dependency>第二步:在类上利用lombok注解。 @Data @NoArgsConstructor @AllArgsConstructor public class Goods { private Long id; private String name; private String remark; private Date createdTime;}第三步:编写单元测试类检测Lombok注解利用 @Slf4j@SpringBootTestpublic class GoodsTests{ @Test void testGoods(){ Goods g=new Goods(); g.setId(100L); g.setName("Lombok"); log.info("id的值为{}",g.getId()); log.info("name的值为{}",g.getName()); }}总结(Summary)本大节次要对lombok做了一个剖析,装置和配置,并结合实际我的项目解说了lombok的利用场景及具体利用过程。

October 19, 2020 · 1 min · jiezi

关于springboot:09springboot工程中的热部署实现

热部署简介Spring Boot 开发者为Spring Boot我的项目中提供了一个热部署(spring-boot-devtools)模块,反对我的项目的热部署(批改了某些资源当前无需重启服务),以进步开发效率.其底层其实是借助了两个类加载器做了具体实现,一个类加载器加载不变class,一个类加载器加载可能变动类,以提供类的热部署性能. 热部署环境初始化本次热部署的演示在IDEA开发中进行实现,其它工具能够本人通过搜索引擎进行学习。 IDEA 启动主动编译,如图所示: IDEA工具中启动注册窗口(按ctrl+shift+alt+/),如图所示: 抉择编译构建配置,如图所示: 热部署在我的项目中利用在须要热部署的我的项目或module中增加如下依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope></dependency>依赖下载当前,可重启reload我的项目,而后当咱们批改了src/main/java目录下的java文件或批改了src/main/resources目录下的配置文件时,默认都会重启你的web服务器,然而批改了测试类或html文件不会主动重启和部署。 总结(summary)本大节对springboot工程中的热部署进行了剖析和实现,能够idea工具中实际整个过程。

October 19, 2020 · 1 min · jiezi

关于springboot:05SpringBoot工程中的MyBatis框架的整合实现及原理分析

整合MyBatis的初步剖析概述Mybatis是一个优良的长久层框架,底层基于JDBC实现与数据库的交互。并在JDBC操作的根底上做了封装和优化,它借助灵便的SQL定制,参数及后果集的映射形式,更好的适应了以后互联网技术的倒退。Mybatis框架的简略利用架构如图所示:在当今的互联网利用中我的项目,mybatis框架通常会由spring框架进行资源整合,作为数据层技术实现数据交互操作。 筹备工作第一步:创立我的项目module,例如:第二步:增加依赖 mysql 驱动依赖 <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope></dependency>spring jdbc 依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId></dependency>mybatis starter依赖 <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version></dependency> 第二步:application.properties 配置文件中增加繁难配置 连接池配置 spring.datasource.url=jdbc:mysql:///dbgoods?serverTimezone=GMT%2B8&characterEncoding=utf8spring.datasource.username=rootspring.datasource.password=rootmybatis配置 mybatis.mapper-locations=classpath:/mapper/*/*.xml环境测试代码实现在src/test/java目录中增加测试类,对mybatis框架整合进行根本测试,代码如下: package com.cy.pj.goods.dao;import java.sql.Connection;import org.apache.ibatis.session.SqlSession;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;@SpringBootTestpublic class MyBatisTests { @Autowired private SqlSession sqlSession; @Test public void testGetConnection() { Connection conn=sqlSession.getConnection(); System.out.println("connection="+conn); }}在SpringBoot脚手架工程中,Spring框架会基于MyBatis框架底层配置,创立SqlSessionFactory对象,而后再通过此工厂对象创立SqlSession,最初基于Springku框架为测试类注入SqlSession对象,接下来,咱们能够通过SqlSession对象实现与数据库的会话了。 整合MyBatis业务代码实现及原理剖析业务形容基于SpringBoot脚手架工程对MyBatis框架的整合,实现对商品库中商品数据的查问业务。 API架构设计 业务时序图剖析 业务代码设计及实现第一步:定义商品模块POJO对象类型(基于此对象存储商品数据),代码如下: package com.cy.pj.goods.pojo;import java.util.Date;/**用于存储商品信息的pojo对象*/public class Goods { private Long id; private String name; private String remark; private Date createdTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Date getCreatedTime() { return createdTime; } public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; }}第二步:定义商品模块长久层对象GoodsDao接口及办法映射,代码如下 ...

October 19, 2020 · 2 min · jiezi

关于springboot:11SpringBoot-工程中的异常处理方式

背景剖析在我的项目的开发中,不论是对底层的数据逻辑操作过程,还是业务逻辑的处理过程,还是管制逻辑的处理过程,都不可避免会遇到各种可预知的、不可预知的异样。解决好异样对系统有很好的爱护作用,同时会大大提高用户的体验。 异样解决剖析概述Java我的项目中解决异样形式无非两种,要么执行trycatch操作,要么执行throw操作(抛给其它对象解决),无论采纳哪种形式,其目标是让咱们的系统对异样要有反馈。但当初的问题是咱们如何让这种反馈代码的编写即简略又直观、敌对。 解决标准咱们在解决异样的过程中通常要遵循肯定的设计规范,例如: 捕捉异样时与抛出的异样必须齐全匹配,或者捕捉异样是抛出异样的父类类型。防止间接抛出RuntimeException,更不容许抛出Exception或者Throwable,应应用有业务含意的自定义异样(例如ServiceException)。捕捉异样后必须进行解决(例如记录日志)。如果不想解决它,须要将异样抛给它的调用者。最外层的逻辑必须解决异样,将其转化成用户能够了解的内容。避免出现反复的代码(Don’t Repeat Yourself),即DAY准则。SpringBoot 工程下的异样解决筹备工作第一步:创立我的项目或module,并增加web依赖,代码如下: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>第二步:批改我的项目拜访端口为80,例如 server.port=80第三步:定义Controller类,代码如下: package com.cy.pj.arithmetic.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controllerpublic class ArithmeticController { @RequestMapping("doCompute/{n1}/{n2}") @ResponseBody public String doCompute(@PathVariable Integer n1, @PathVariable Integer n2){ Integer result=n1/n2; return "Result is "+result; }}第四步启动我的项目进行拜访测试 在浏览器地址栏输出http://localhost/doCompute/10/2,检测输入后果。 Result is 5默认异样解决在浏览器地址栏输出http://localhost/doCompute/10/0,检测输入后果。 对于这样的默认异样解决(spring boot提供),用户体验不太敌对,为了出现更加敌对的异样信息,咱们通常要对异样进行自定义解决。 本人try异样解决在管制层办法中,咱们能够进行try catch解决,例如: @RequestMapping("doCompute/{n1}/{n2}") @ResponseBody public String doCompute(@PathVariable Integer n1, @PathVariable Integer n2){ try{ Integer result=n1/n2; return "Result is "+result; }catch(ArithmeticException e){ return "exception is "+e.getMessage(); } } 一个Controller类中通常会有多个办法,这样多个办法中都写try语句进行异样解决会带来大量反复代码的编写,不易保护。 ...

October 19, 2020 · 1 min · jiezi

关于springboot:13SpringBoot工程下活动Activity模块设计及实现

业务形容基于Spring,MyBatis,SpringBoot,Thymeleaf,Ajax技术实现流动模块的查问,增加等操作。 我的项目环境初始化筹备工作1. MySQL(5.7)2. JDK (1.8)3. Maven (3.6.3)4. STS(4.7.1)数据库初始化关上mysql控制台,而后按如下步骤执行goods.sql文件。 第一步:登录mysql。 mysql –uroot –proot第二步:设置控制台编码方式。 set names utf8;第三步:执行activity.sql文件(切记不要关上文件复制到mysql客户端运行)。 source d:/activity.sql其中activity.sql文件内容如下: drop database if exists dbactivity;create database dbactivity default character set utf8;use dbactivity;create table tb_activity( id bigint primary key auto_increment, title varchar(100) not null, category varchar(100) not null, startTime datetime not null, endTime datetime not null, remark text, state tinyint, createdTime datetime not null, createdUser varchar(100))engine=InnoDB;insert into tb_activity values (null,'ABS','cuoxiao','2020-02-02 15:00:00','2020-02-03 15:00:00','...',1,now(),'xiaoli');insert into tb_activity values (null,'VALIDATE','cuoxiao','2020-02-02 15:00:00','2020-02-03 15:00:00','...',1,now(),'xiaoli');insert into tb_activity values (null,'VALIDATE','cuoxiao','2020-02-02 15:00:00','2020-02-03 15:00:00','...',1,now(),'xiaoli');insert into tb_activity values (null,'ABS','cuoxiao','2020-02-02 15:00:00','2020-02-03 15:00:00','...',1,now(),'xiaoli');insert into tb_activity values (null,'ACCESS','cuoxiao','2020-02-02 15:00:00','2020-02-03 15:00:00','...',1,now(),'xiaoli');创立我的项目并增加依赖第一步:基于start.spring.io 创立我的项目并设置根本信息。第二步:创立我的项目时指定我的项目外围依赖。第三步:我的项目创立当前剖析其构造。 ...

October 19, 2020 · 3 min · jiezi

关于springboot:07SpringBootMyBatisSpring技术整合实现商品模块的CRUD操作

业务形容基于Spring,MyBatis,SpringBoot,Thymeleaf技术实现商品模块的增删改查操作。 我的项目环境初始化筹备工作1. MySQL(5.7)2. JDK (1.8)3. Maven (3.6.3)4. STS(4.7.1)数据库初始化关上mysql控制台,而后按如下步骤执行goods.sql文件。 第一步:登录mysql。 mysql –uroot –proot第二步:设置控制台编码方式。 set names utf8;第三步:执行goods.sql文件(切记不要关上文件复制到mysql客户端运行)。 source d:/goods.sql其中goods.sql文件内容如下: drop database if exists dbgoods;create database dbgoods default character set utf8;use dbgoods;create table tb_goods( id bigint primary key auto_increment, name varchar(100) not null, remark text, createdTime datetime not null)engine=InnoDB;insert into tb_goods values (null,'java','very good',now());insert into tb_goods values (null,'mysql','RDBMS',now());insert into tb_goods values (null,'Oracle','RDBMS',now());insert into tb_goods values (null,'java','very good',now());insert into tb_goods values (null,'mysql','RDBMS',now());insert into tb_goods values (null,'Oracle','RDBMS',now());insert into tb_goods values (null,'java','very good',now());创立我的项目并增加依赖基于STS创立第一步:基于start.spring.io 创立我的项目并设置根本信息第二步:创立我的项目时指定我的项目外围依赖第三步:我的项目创立当前剖析其构造 ...

October 19, 2020 · 3 min · jiezi

关于springboot:15基于SpringMyBatisSpringBootVue技术实现购物券系统的增删改查操作

业务形容基于Spring,MyBatis,SpringBoot,Thymeleaf技术实现购物券的增删改查操作。 我的项目环境初始化筹备工作1. MySQL(5.7)2. JDK (1.8)3. Maven (3.6.3)4. IDEA(2020.2)数据库初始化关上mysql控制台,而后按如下步骤执行dbretail.sql文件。 第一步:登录mysql。 mysql –uroot –proot第二步:设置控制台编码方式。 set names utf8;第三步:执行dbretail.sql文件(切记不要关上文件复制到mysql客户端运行)。 source d:/dbretail.sql其中dbvoucher.sql文件内容如下: drop database if exists dbretail;create database dbretail default character set utf8;use dbretail;CREATE TABLE tb_voucher( `id` INT UNSIGNED PRIMARY KEY AUTO_INCREMENT COMMENT '主键', `deno` DECIMAL(10,2) UNSIGNED NOT NULL COMMENT '面值', `requirement` DECIMAL(10,2) UNSIGNED NOT NULL COMMENT '订单多少钱能够应用', `startTime` DATETIME COMMENT '起始日期', `endTime` DATETIME COMMENT '截至日期', `maxNum` INT COMMENT '代金卷发放最大数量', `remark` varchar(200) COMMENT '备注', `createdTime` DATETIME COMMENT '创立日期') COMMENT='购物券表';insert into tb_voucher values (null,100,1000,'2020/05/07','2020/06/07',200,'Remark',now());insert into tb_voucher values (null,80,800,'2020/05/07','2020/06/07',300,'Remark',now());insert into tb_voucher values (null,50,500,'2020/05/07','2020/06/07',400,'Remark',now());insert into tb_voucher values (null,30,300,'2020/05/07','2020/06/07',500,'Remark',now());insert into tb_voucher values (null,10,100,'2020/05/07','2020/06/07',600,'Remark',now());创立我的项目并增加依赖基于IDEA创立第一步:创立Empty我的项目并设置根本信息(如果Empty我的项目曾经存在则无需创立) ...

October 19, 2020 · 5 min · jiezi

关于springboot:04SpringBoot工程下如何实现对HikariCP链接池的整合

池化思维剖析池化思维是咱们我的项目开发过程中的一种十分重要的思维,如整数池,字符串池,对象池、连接池、线程池等都是池化思维的一种利用,都是通过复用对象,以缩小因创立和开释对象所带来的资源耗费,进而来晋升零碎性能。例如Integer对象的外部池利用,代码如下: package com.cy.java.pool;public class TestInteger01 { public static void main(String[] args) { Integer n1=100;//Integer.valueOf(100) 编译时优化 Integer n2=100; Integer n3=200; Integer n4=200;//池中没有则new Integer(200) System.out.println(n1==n2);//true System.out.println(n3==n4);//false } }数据库连接池简介背景剖析目开发过程中应用程序与数据库交互时,“取得连贯”或“开释连贯”是十分耗费系统资源的两个过程,频繁地进行数据库连贯的建设和敞开会极大影响零碎的性能,若多线程并发量很大,这样耗时的数据库连贯就可能让零碎变得卡顿。因为TCP连贯的创立开销非常低廉,并且数据库所能承载的TCP并发连接数也有限度,针对这种场景,数据库连接池应运而生。如下图所示:思考:如果当初是让你去设计一个连接池,你会从什么角度进行设计?第一:物理存储构造(基于什么构造去存储数据)第二:基于什么算法从池中取连贯?第三:基于什么算法从池中移除连贯?第四:当池中没有连贯时,基于什么形式解决连贯申请?第五:池是能够共享,咱们须要思考池在拜访的时并发平安? 连接池原理剖析在零碎初始化的时候,在内存中开拓一片空间,将肯定数量的数据库连贯作为对象存储在对象池里,并对外提供数据库连贯的获取和偿还办法。用户拜访数据库时,并不是建设一个新的连贯,而是从数据库连接池中取出一个已有的闲暇连贯对象;应用结束偿还后的连贯也不会马上敞开,而是由数据库连接池对立治理回收,为下一次借用做好筹备。如果因为高并发申请导致数据库连接池中的连贯被借用结束,其余线程就会期待,直到有连贯被偿还。整个过程中,连贯并不会敞开,而是源源不断地循环应用,有借有还。数据库连接池还能够通过设置其参数来管制连接池中的初始连接数、连贯的上上限数,以及每个连贯的最大应用次数、最大闲暇工夫等,也能够通过其本身的管理机制来监督数据库连贯的数量、应用状况等。 Java中的连接池Java官网,为了在应用程序中更好的利用连接池技术,定义了一套数据源标准,例如javax.sql.DataSource接口,基于这个接口,很多团队或集体创立了不同的连接池对象。而后咱们的应用程序中通过耦合与DataSource接口,便能够不便的切换不同厂商的连接池。Java我的项目中通过连接池获取连贯的一个根本过程,如下图所示:在上图中,用户通过DataSource对象的getConnection()办法,获取一个连贯。如果池中有连贯,则间接将连贯返回给用户。如果池中没有连贯,则会调用Dirver(驱动,由数据库厂商进行实现)对象的connect办法从数据库获取,拿到连贯当前,能够将连贯在池中放一份,而后将连贯返回给调用方。连贯需求方再次须要连贯时,能够从池中获取,用完当前再还给池对象。 数据库连接池在Java数据库相干中间件产品群中,应该算是底层最根底的一类产品,作为企业应用开发必不可少的组件,有数蠢才们为咱们奉献了一个又一个的优良产品,它们有的随时代倒退,功成身退,有的则还在一直迭代,老而弥坚,更有新生代产品,或性能无敌,或性能全面。目前市场上常见的连接池有DBCP、C3P0,DRUID,HikariCP等。SpringBoot工程下HikariCP整合测试数据初始化关上mysql控制台,而后按如下步骤执行goods.sql文件。第一步:登录mysql。 mysql –uroot –proot第二步:设置控制台编码方式。 set names utf8;第三步:执行goods.sql文件(切记不要关上文件复制到mysql客户端运行)。 source d:/goods.sql其中goods.sql文件内容如下: drop database if exists dbgoods;create database dbgoods default character set utf8;use dbgoods;create table tb_goods( id bigint primary key auto_increment, name varchar(100) not null, remark text, createdTime datetime not null)engine=InnoDB;insert into tb_goods values (null,'java','very good',now());insert into tb_goods values (null,'mysql','RDBMS',now());insert into tb_goods values (null,'Oracle','RDBMS',now());insert into tb_goods values (null,'java','very good',now());insert into tb_goods values (null,'mysql','RDBMS',now());insert into tb_goods values (null,'Oracle','RDBMS',now());insert into tb_goods values (null,'java','very good',now());创立我的项目Module并增加相干依赖第一步:基于IDEA创立我的项目Module,如图所示:第二步:增加依赖1) mysql数据库驱动依赖。 ...

October 19, 2020 · 2 min · jiezi

关于springboot:02如何基于STS实现SpringBoot工程项目的创建

SpringBoot我的项目环境初始化本次我的项目的创立,须要如下软件已筹备并已实现其配置. 下载、装置、配置JDK(这里抉择JDK8版本)。下载、解压、配置maven(这里抉择3.6.3版本)下载、解压、配置STS(这里抉择4.7.1版本)阐明:对于环境下载,装置配置,本人通过官网或搜索引擎查问实现。 SpringBoot我的项目创立过程剖析及实现基于STS内置start创立第一步:关上sts软件,快捷键ctrl+n关上新建窗口,如图所示: 第二步:输出我的项目相干信息,如图所示:第三步:抉择SpringBoot版本,如图所示:第四步:我的项目构造展现,我的项目创立完当前的构造如下:基于浏览器(Browser)创立第一步:关上浏览器输出start.spring.io,而后输出我的项目信息,进行我的项目构建,如图所示:第二步:将构建并下载下来的我的项目进行解压,如图所示:第三步:将解压好的我的项目导入到sts中,如图所示:第四部步:我的项目构造展现,如图所示:基于STS一般maven形式创立第一步:创立一般maven我的项目,快捷键ctrl+n 搜maven,如图所示:第二步:抉择我的项目骨架,如图所示:第三步:输出像我的项目信息,如图所示:第四步:我的项目构造展现,如图所示: 第五步:将已有我的项目的pom文件,我的项目启动类,配置文件拷贝到maven工程中,并进行适当批改,例如批改一下pom文件中项目名称.SpringBoot我的项目创立过程问题剖析JDK装置配置问题本地装置的JDK短少资源,如图所示:Maven配置及更新问题Maven的配置文件谬误,如图所示:Maven中不能有多个私服镜像,如图所示Maven我的项目依赖下载更新问题网络连接(Connect)问题spring 官网服务器连贯超时.总结(Summary)本大节重点解说了基于STS工具创立和导入SpringBoot工程的几种形式以及在实际过程的一些问题的思考和解决方案。

October 19, 2020 · 1 min · jiezi

关于springboot:01如何理解-Spring-Boot技术

Spring Boot 背景剖析JAVAEE利用体系中沉重的配置、低下的开发效率、高难度的三方集成,简单的部署流程等等始终被开发人员所诟病。即便是应用Spring这样的轻量级的资源整合框架,在实现其绝对比拟多的资源整合时,仍旧须要大量的手动依赖治理,简单的XML配置(还常常没有提醒)。还有就是当初的软件生态利用也曾经造成肯定的规模,零碎架构正在从单体架构,分布式架构,逾越到微服务架构。随着整个架构体系的变动,企业对技术的要求也在变动,当初的企业更重视技术的开箱即用,更重视技术在生态圈中的深度交融,更重视轻量级的运维。由此由此spring boot诞生。 Spring Boot 要解决什么问题Spring Boot是由Pivotal团队提供的全新的Java软件开发框架(很多人当初把它了解为一个脚手架),其设计目标是用来简化Spring我的项目的初始搭建以及开发过程。该框架应用了特定的注解形式来进行配置,从而使开发人员不再须要大量的xml配置。不再须要大量的手动依赖治理。Spring Boot基于疾速构建理念,通过约定大于配置,开箱即用的形式,心愿可能在蓬勃发展的疾速利用开发畛域成为其领导者。 Spring Boot 有哪些外围的要害个性起步依赖(Starter Dependency)。主动配置(Auto Configuration)。健康检查(Actator)-监控。嵌入式服务(Tomcat,Jetty)。总结(Summary)总之,Spring Boot 框架就是要基于疾速构建理念,基于约定大于配置形式,实现技术的开箱即用,以进步开发效率。

October 19, 2020 · 1 min · jiezi

关于springboot:15基于SpringMyBatisSpringBootVue技术实现购物券的增删改查操作

业务形容基于Spring,MyBatis,SpringBoot,Thymeleaf技术实现购物券的增删改查操作。 我的项目环境初始化筹备工作1. MySQL(5.7)2. JDK (1.8)3. Maven (3.6.3)4. IDEA(2020.2)数据库初始化关上mysql控制台,而后按如下步骤执行dbretail.sql文件。 第一步:登录mysql。 mysql –uroot –proot第二步:设置控制台编码方式。 set names utf8;第三步:执行dbretail.sql文件(切记不要关上文件复制到mysql客户端运行)。 source d:/dbretail.sql其中dbvoucher.sql文件内容如下: drop database if exists dbretail;create database dbretail default character set utf8;use dbretail;CREATE TABLE tb_voucher( `id` INT UNSIGNED PRIMARY KEY AUTO_INCREMENT COMMENT '主键', `deno` DECIMAL(10,2) UNSIGNED NOT NULL COMMENT '面值', `condition` DECIMAL(10,2) UNSIGNED NOT NULL COMMENT '订单多少钱能够应用', `startTime` DATETIME COMMENT '起始日期', `endTime` DATETIME COMMENT '截至日期', `maxNum` INT COMMENT '代金卷发放最大数量', `remark` varchar(200) COMMENT '备注', `createdTime` DATETIME COMMENT '创立日期') COMMENT='购物券表';insert into tb_voucher values (null,100,1000,'2020/05/07','2020/06/07',200,'Remark',now());insert into tb_voucher values (null,80,800,'2020/05/07','2020/06/07',300,'Remark',now());insert into tb_voucher values (null,50,500,'2020/05/07','2020/06/07',400,'Remark',now());insert into tb_voucher values (null,30,300,'2020/05/07','2020/06/07',500,'Remark',now());insert into tb_voucher values (null,10,100,'2020/05/07','2020/06/07',600,'Remark',now());创立我的项目并增加依赖基于IDEA创立第一步:创立Empty我的项目并设置根本信息(如果Empty我的项目曾经存在则无需创立) ...

October 18, 2020 · 4 min · jiezi

关于springboot:0101javase02maven03Spring-Initializr

01-javase01.1创立并运行java module01.1.1在IDEA关上的我的项目中创立Java Module,如图所示: 01.1.2在创立Java Module的界面,抉择Next,输出module名,如图所示: 01.1.3Java Module创立好当前的构造,如图所示: 01.1.4在我的项目模块01-javase中创立包,例如: 01.1.5在指定包中创立类,如图所示: 01.1.6运行Java类,如图所示: 01.2代码01.2.1HelloWorld 01.2.2IntegerTests 02-maven02.1创立并运行Maven Module02.1.1在我的项目中,创立maven module,如图所示: 02.1.2接下来,输出module根本信息,如图所示: 02.1.13关上pom.xml文件,增加Junit依赖,如图所示: 02.1.4创立包、单元测试类和办法,进行单元测试,如图所示: 02.2代码02.2.1MavenTests 03-Spring Initializr03.1创立我的项目03.1.1在我的项目中,创立Spring Initializr Module,如图所示: 03.1.2接下来输出Spring Initializr Module信息,如图所示: 03.1.3抉择springboot版本,依赖,而后进入一下,如图所示: 输出module信息,而后实现Module的创立,如图所示: Spring Initializr Module创立好当前,其构造如图所示: 03.2配置我的项目03.2.1Module创立好当前,能够关上pom.xml文件,批改其03.2.2springboot版本,如图所示: 03.2.3SpringBoot 版本批改好当前(可选),向pom.xml右键,抉择Add as Maven Project 选项,进行maven我的项目构建(此时才会springboot 依赖下载和编译),例如: 03.3运行Spring Initializr Module03.3.1Module 构建实现,关上启动类运行module,如图所示: 03.3.2Module胜利启动和运行后果,如图所示:

October 18, 2020 · 1 min · jiezi

关于springboot:05SpringBootMyBatisSpring-技术整合实现商品模块的CRUD操作转

业务形容基于Spring,MyBatis,SpringBoot,Thymeleaf技术实现商品模块的增删改查操作。 我的项目环境初始化筹备工作1. MySQL(5.7)2. JDK (1.8)3. Maven (3.6.3)4. STS(4.7.1)数据库初始化关上mysql控制台,而后按如下步骤执行goods.sql文件。第一步:登录mysql。 mysql –uroot –proot第二步:设置控制台编码方式。 set names utf8;第三步:执行goods.sql文件(切记不要关上文件复制到mysql客户端运行)。 source d:/goods.sql其中goods.sql文件内容如下: drop database if exists dbgoods;create database dbgoods default character set utf8;use dbgoods;create table tb_goods( id bigint primary key auto_increment, name varchar(100) not null, remark text, createdTime datetime not null)engine=InnoDB;insert into tb_goods values (null,'java','very good',now());insert into tb_goods values (null,'mysql','RDBMS',now());insert into tb_goods values (null,'Oracle','RDBMS',now());insert into tb_goods values (null,'java','very good',now());insert into tb_goods values (null,'mysql','RDBMS',now());insert into tb_goods values (null,'Oracle','RDBMS',now());insert into tb_goods values (null,'java','very good',now());创立我的项目并增加依赖基于STS创立第一步:基于start.spring.io 创立我的项目并设置根本信息 ...

October 18, 2020 · 3 min · jiezi

关于springboot:04SpringBoot-工程中的异常处理方式转

背景剖析在我的项目的开发中,不论是对底层的数据逻辑操作过程,还是业务逻辑的处理过程,还是管制逻辑的处理过程,都不可避免会遇到各种可预知的、不可预知的异样。解决好异样对系统有很好的爱护作用,同时会大大提高用户的体验。 异样解决剖析概述Java我的项目中解决异样形式无非两种,要么执行trycatch操作,要么执行throw操作(抛给其它对象解决),无论采纳哪种形式,其目标是让咱们的系统对异样要有反馈。但当初的问题是咱们如何让这种反馈代码的编写即简略又直观、敌对。 解决标准咱们在解决异样的过程中通常要遵循肯定的设计规范,例如: 捕捉异样时与抛出的异样必须齐全匹配,或者捕捉异样是抛出异样的父类类型。防止间接抛出RuntimeException,更不容许抛出Exception或者Throwable,应应用有业务含意的自定义异样(例如ServiceException)。捕捉异样后必须进行解决(例如记录日志)。如果不想解决它,须要将异样抛给它的调用者。最外层的逻辑必须解决异样,将其转化成用户能够了解的内容。避免出现反复的代码(Don’t Repeat Yourself),即DAY准则。SpringBoot 工程下的异样解决筹备工作第一步:创立我的项目或module,并增加web依赖,代码如下: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>第二步:批改我的项目拜访端口为80,例如 server.port=80第三步:定义Controller类,代码如下: package com.cy.pj.arithmetic.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controllerpublic class ArithmeticController { @RequestMapping("doCompute/{n1}/{n2}") @ResponseBody public String doCompute(@PathVariable Integer n1, @PathVariable Integer n2){ Integer result=n1/n2; return "Result is "+result; }}第四步启动我的项目进行拜访测试 在浏览器地址栏输出http://localhost/doCompute/10/2,检测输入后果。 Result is 5默认异样解决在浏览器地址栏输出http://localhost/doCompute/10/0,检测输入后果。 对于这样的默认异样解决(spring boot提供),用户体验不太敌对,为了出现更加敌对的异样信息,咱们通常要对异样进行自定义解决。 本人try异样解决在管制层办法中,咱们能够进行try catch解决,例如: @RequestMapping("doCompute/{n1}/{n2}") @ResponseBody public String doCompute(@PathVariable Integer n1, @PathVariable Integer n2){ try{ Integer result=n1/n2; return "Result is "+result; }catch(ArithmeticException e){ return "exception is "+e.getMessage(); } } 一个Controller类中通常会有多个办法,这样多个办法中都写try语句进行异样解决会带来大量反复代码的编写,不易保护。 ...

October 18, 2020 · 1 min · jiezi

关于springboot:02如何基于STS实现SpringBoot-工程项目的创建转

SpringBoot我的项目环境初始化本次我的项目的创立,须要如下软件已筹备并已实现其配置. 下载、装置、配置JDK(这里抉择JDK8版本)。下载、解压、配置maven(这里抉择3.6.3版本)下载、解压、配置STS(这里抉择4.7.1版本)阐明:对于环境下载,装置配置,本人通过官网或搜索引擎查问实现。 SpringBoot我的项目创立过程剖析及实现基于STS内置start创立第一步:关上sts软件,快捷键ctrl+n关上新建窗口,如图所示: 第二步:输出我的项目相干信息,如图所示: 第三步:抉择SpringBoot版本,如图所示: 第四步:我的项目构造展现,我的项目创立完当前的构造如下: 基于浏览器(Browser)创立第一步:关上浏览器输出start.spring.io,而后输出我的项目信息,进行我的项目构建,如图所示: 第二步:将构建并下载下来的我的项目进行解压,如图所示: 第三步:将解压好的我的项目导入到sts中,如图所示: 第四部步:我的项目构造展现,如图所示: 基于STS一般maven形式创立第一步:创立一般maven我的项目,快捷键ctrl+n 搜maven,如图所示: 第二步:抉择我的项目骨架,如图所示: 第三步:输出像我的项目信息,如图所示: 第四步:我的项目构造展现,如图所示: 第五步:将已有我的项目的pom文件,我的项目启动类,配置文件拷贝到maven工程中,并进行适当批改,例如批改一下pom文件中项目名称.SpringBoot我的项目创立过程问题剖析JDK装置配置问题本地装置的JDK短少资源,如图所示: Maven配置及更新问题Maven的配置文件谬误,如图所示: Maven中不能有多个私服镜像,如图所示 Maven我的项目依赖下载更新问题 网络连接(Connect)问题spring 官网服务器连贯超时. 总结(Summary)本大节重点解说了基于STS工具创立和导入SpringBoot工程的几种形式以及在实际过程的一些问题的思考和解决方案。

October 18, 2020 · 1 min · jiezi

关于springboot:01如何理解-Spring-Boot技术

Spring Boot 背景剖析JAVAEE利用体系中沉重的配置、低下的开发效率、高难度的三方集成,简单的部署流程等等始终被开发人员所诟病。即便是应用Spring这样的轻量级的资源整合框架,在实现其绝对比拟多的资源整合时,仍旧须要大量的手动依赖治理,简单的XML配置(还常常没有提醒)。还有就是当初的软件生态利用也曾经造成肯定的规模,零碎架构正在从单体架构,分布式架构,逾越到微服务架构。随着整个架构体系的变动,企业对技术的要求也在变动,当初的企业更重视技术的开箱即用,更重视技术在生态圈中的深度交融,更重视轻量级的运维。由此由此spring boot诞生。 Spring Boot 要解决什么问题Spring Boot是由Pivotal团队提供的全新的Java软件开发框架(很多人当初把它了解为一个脚手架),其设计目标是用来简化Spring我的项目的初始搭建以及开发过程。该框架应用了特定的注解形式来进行配置,从而使开发人员不再须要大量的xml配置。不再须要大量的手动依赖治理。Spring Boot基于疾速构建理念,通过约定大于配置,开箱即用的形式,心愿可能在蓬勃发展的疾速利用开发畛域成为其领导者。 Spring Boot 有哪些外围的要害个性起步依赖(Starter Dependency)。主动配置(Auto Configuration)。健康检查(Actator)-监控。嵌入式服务(Tomcat,Jetty)。Spring Boot 的集体了解及面试材料查找springboot是用来整合框架的 1.Spring Boot、Spring MVC 和 Spring 有什么区别?========================================== SpringFramework 最重要的特色是依赖注入。所有 SpringModules 不是依赖注入就是 IOC 管制反转。当咱们失当的应用 DI 或者是 IOC 的时候,咱们能够开发松耦合利用。松耦合利用的单元测试能够很容易的进行。 SpringMVC Spring MVC 提供了一种分离式的办法来开发 Web 利用。通过使用像 DispatcherServelet,MoudlAndView 和 ViewResolver 等一些简略的概念,开发 Web 利用将会变的非常简单。SpringBoot Spring 和 SpringMVC 的问题在于须要配置大量的参数。Spring Boot 通过一个主动配置和启动的项来目解决这个问题。为了更快的构建产品就绪应用程序,Spring Boot 提供了一些非功能性特色。 2.什么是主动配置?咱们是否带来更多的智能?当一个 MVC JAR 增加到应用程序中的时候,咱们是否主动配置一些 beans?Spring 和 SpringMVC 的问题在于须要配置大量的参数。 Spring 查看(CLASSPATH 上可用的框架)已存在的应用程序的配置。在此基础上,Spring Boot 提供了配置应用程序和框架所须要的根本配置。这就是主动配置。 ...

October 18, 2020 · 2 min · jiezi

关于springboot:15SpringBoot工程中前端JS问题调试分析

我的项目中客户端JS常见问题 总结(Summary)本大节次要是列出了几个客户端常见问题,这些问题的解决要联合业务进行断点,日志,排除法进行剖析,而后从实际中进行进步.

October 18, 2020 · 1 min · jiezi

关于springboot:15SpringBoot工程中前端JS问题调试分析

我的项目中客户端JS常见问题 总结(Summary)本大节次要是列出了几个客户端常见问题,这些问题的解决要联合业务进行断点,日志,排除法进行剖析,而后从实际中进行进步.

October 16, 2020 · 1 min · jiezi

关于springboot:springboot1简介

用Maven我的项目创立Spring利用创立maven工程在pom.xml中导入Spring Boot相干依赖<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <!--SpringBoot版本--> <version>1.5.9.RELEASE</version></parent><dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency></dependencies>3.编写主程序 package hello;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class springHello { public static void main(String[] args){ SpringApplication.run(springHello.class,args); }}4.编写相干的Controler、Service package hello.controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@org.springframework.stereotype.Controllerpublic class Controller { @ResponseBody @RequestMapping("/hello") public String hello(){ return "Hello World!"; }}5.测试启动main函数6.部署(1)首先把maven插件依赖写入pom.xml,这个maven插件能够把我的项目打包为jar包 <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins></build>(2)maven-->申明周期-->package,失去jar包(3)java -jar 我的项目名 总结:创立Maven我的项目-->导入父我的项目和用到模块的场景启动器-->写主程序-->写业务逻辑Spring Boot原理流程:写主程序启动SpringBoot利用-->依照业务逻辑写Controller、Service,不再须要配置其余货色为何SpringBoot不须要配置其余货色:剖析pom.xml点击pom.xml的父我的项目spring-boot-starter-parent,进入后点击父我的项目的父我的项目spring-boot-dependencies,发现里边定义了各种依赖的版本。即父父我的项目真正治理SpringBoot的所有依赖,是版本仲裁核心。所以咱们导入依赖时默认不须要写版本(父父我的项目中没定义的除外)导入依赖(场景启动器)。springboot将所有性能场景抽取进去,做成starter。咱们须要啥性能,就导入相干的starter用Spring我的项目创立springboot利用抉择好导入的场景启动器后,父我的项目和场景启动器主动增加,主程序也有了。咱们只有分心写业务逻辑就行了有三个文件是没用的,能够删除掉resources中有三个文件夹 (1)static:保留所有的动态资源,如js、css、图片等(2)templates:保留所有的模板页html。springboot默认的jar包应用嵌入式tomcat,不反对jsp页面,但咱们可应用模板引擎(freemarker、thymeleaf)解决问题(3)application.properities:springboot利用的配置文件,咱们能够写他来批改默认设置

October 16, 2020 · 1 min · jiezi

关于springboot:14SpringBootMybatisVue-实现商品模块的crud操作

筹备工作第一步 创立新module,名字为10-springboot-goods-vue.第二步 增加maven依赖并进行初步配置(拷贝即可)第三步 拷贝pojo,dao,service包中的所有接口和类.第四步 拷贝动态资源到static目录(例如vue.js,axios.min.js) 商品查问设计及实现创立GoodsController并定义相干办法,代码如下: package com.cy.pj.goods.controller;import com.cy.pj.goods.pojo.Goods;import com.cy.pj.goods.service.GoodsService;import java.util.List;@RestControllerpublic class GoodsController { @Autowired private GoodsService goodsService; /**查问所有商品信息*/ @GetMapping("/goods/doFindGoods") public List<Goods> doFindGoods(){ return goodsService.findGoods(); }}在我的项目static目录创立goods-vue.html,并基于vue出现数据,代码如下 <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <div id="app"> <h1>The Goods Page</h1> <table> <thead> <tr> <th>id</th> <th>name</th> <th>remark</th> <th>createdTime</th> </tr> </thead> <tbody> <tr v-for="g in goods"> <td>{{g.id}}</td> <td>{{g.name}}</td> <td>{{g.remark}}</td> <td>{{g.createdTime}}</td> </tr> </tbody> </table> </div> <script src="js/axios.min.js"></script> <script src="js/vue.js"></script> <script> var vm=new Vue({//vue对象时vue.js利用的入口对象 el:"#app",//vue对象要监控的区域 data:{//此对象用于同步页面数据的一个对象 goods:{} }, methods:{//同步与页面元素事件处理函数 doFindGoods:function(){ let url="goods/doFindGoods"; axios.get(url) .then(function(result){ this.vm.goods=result.data; }); } }, mounted:function(){ this.doFindGoods(); } }); </script></body></html>启动tomcat进行拜访测试,如图所示: ...

October 15, 2020 · 1 min · jiezi

关于springboot:SpringBoot整合SpringMVC框架

前言:该文章是基于 SpringBoot整合MyBatis框架疾速入门 文章的根底上实现的下列性能。 SpringMVC框架概述:SpringMVC 是一种基于 Java 实现 MVC 设计模型的申请驱动类型的轻量级 Web 框架。它通过一套注解,让一个简略的 Java 类成为解决申请的控制器,而无须实现任何接口。 后期筹备1.编辑pom.xml文件,增加Spring web依赖,Thymeleaf依赖Web依赖(提供了Spring MVC外围API,同时会嵌入一个Tomcat服务器) <!-- 增加Spring web依赖 --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>Thymeleaf依赖(提供了一个视图解析器对象以及数据绑定机制) <!-- 增加Thymeleaf依赖 --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>2.在application.properties中增加视图解析器配置# server portserver.port=80# Spring thymeleaf# 批改页面不须要重启服务器spring.thymeleaf.cache=falsespring.thymeleaf.prefix=classpath:/templates/pages/spring.thymeleaf.suffix=.html3.Spring MVC进行编码实现3.1 创立工程 3.2 编写GoodsMapper.xml文件<?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.cy.pj.goods.dao.GoodsDao"> <!-- 查问所有用户信息 --> <select id="findAll" resultType="com.cy.pj.goods.utils.User"> select * from emp </select></mapper>3.3 编写GoodsDao接口package com.cy.pj.goods.dao;import java.util.List;import org.apache.ibatis.annotations.Mapper;import com.cy.pj.goods.utils.User;/** * @Mapper 用于形容(做标记)数据层拜访接口,用于通知mybatis框架 * 应用此注解形容的接口要由底层为创立实现类,在实现类中基于mybatis * API实现与数据库的交互,这个类的对象最初会交给Spring治理。 */@Mapperpublic interface GoodsDao { /** * 查问所有用户信息 * @return List汇合 */ public List<User> findAll();}3.4 编写GoodsService接口package com.cy.pj.goods.service;import java.util.List;import com.cy.pj.goods.utils.User;/** * 用户模块的业务层接口,用于制订规范 * @author BigData * */public interface GoodsService { /** * 查问所有用户信息 * @return 全副信息 */ public List<User> findAll();}3.5 编写GoodsServiceImpl类该类实现了GoodsService接口,用于用于用户模块的业务的具体实现 ...

October 14, 2020 · 1 min · jiezi

关于springboot:适合初中级Java程序员修炼手册从0搭建整个Web项目一

前言文本已收录至我的GitHub仓库,欢送Star:https://github.com/bin392328206 > 种一棵树最好的工夫是十年前,其次是当初six-finger-web一个Web后端框架的轮子从解决Http申请【基于Netty的申请级Web服务器】 到mvc【接口封装转发)】,再到ioc【依赖注入】,aop【切面】,再到 rpc【近程过程调用】最初到orm【数据库操作】全副本人撸一个(繁难)的轮子。github 为啥要写这个轮子其实是这样的,小六六本人平时呢?有时候喜爱看看人家的源码比方Spring,然而小六六的程度可能不怎么样,每次看都看得昏头昏脑,而后就感觉外面的细节太难了,而后我就只能观其总体的思维,而后我就想我如果能够依据各位前辈的一些思考,本人撸一个简略的轮子进去,那我前面去了解作者的思维是不是简略点呢?于是呢 six-finger-web就面世了,它其实就是我的一个学习过程,而后我把它开源进去,心愿能帮忙那些对于学习源码有艰难的同学。还有就是能够锤炼一下本人的编码能力,因为平时咱们总是crud用的Java api都是那些,长此以往,很多框架类的api咱们基本就不纯熟了,所以借此机会,锤炼一下。 特点内置由 Netty 编写 HTTP 服务器,无需额定依赖 Tomcat 之类的 web 服务(刚好小六六把Netty系列写完,顺便用下)代码简略易懂(小六六本人写不出框架大佬那种高类聚,低耦合的代码),能力略微强一点看代码就能懂,弱点的也没关系,小六六有配套的从0搭建教程。反对MVC相干的注解确保和SpringMVC的用法相似反对Spring IOC 和Aop相干性能反对相似于Mybatis相干性能反对相似于Dubbo的rpc相干性能对于数据返回,只反对Json格局絮叨此教程只适宜初中级程度,因为作者自身程度不高,不喜勿喷,明天是文章的第一篇,所以先写的是 由Netty 搭建一个http服务器 应用Netty实现HTTP服务器Netty是一个异步事件驱动的网络应用程序框架用于疾速开发可保护的高性能协定服务器和客户端。Netty通过精心设计,具备丰盛的协定,如FTP,SMTP,HTTP以及各种二进制和基于文本的传统协定。Java程序员在开发web利用的时候,咱们习惯于基于servlet标准,来做后端开发,就比方咱们的SpringMVC其本质也是一个servlet,至于spring Webfux,我不晓得有多少公司应用了,然而目前为止2020,咱们公司是没有应用的,这次呢咱们就试试用Netty来实现一下,其实这个很简略,以前的我写Netty系列的时候,我曾经写过了,大家能够去找找https://github.com/bin3923282... 首先是创立我的项目因为咱们这个是six-finger-web的第一篇,所以我尽量把点点滴滴做到首先创立一个maven我的项目,如果这个都不会的话,小六六倡议先学习根底再来,在文章很多的中央,一些根底的小六六是默认你懂,如果有啥不懂的能够上github上找我联系方式,我如果有空会给大家解答的 创立pom.xml<?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.xiaoliuliu</groupId> <artifactId>six-finger-web</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <dependencies> <!-- 为了代码简洁引入lombok,不须要再写setter和getter(能够不引入)--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> <scope>provided</scope> </dependency> <!--动静代理相干--> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.1</version> </dependency> <!-- Netty相干--> <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.51.Final</version> </dependency> </dependencies></project>HttpServerNetty 编写 HTTP 服务器主类 package com.xiaoliuliu.six.finger.web.server;import io.netty.bootstrap.ServerBootstrap;import io.netty.channel.ChannelFuture;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.nio.NioServerSocketChannel;import io.netty.handler.logging.LogLevel;import io.netty.handler.logging.LoggingHandler;import java.net.InetSocketAddress;/** * @author 小六六 * @version 1.0 * @date 2020/10/13 11:41 * Netty 编写 HTTP 服务器 * 主类 */public class HttpServer { /** * @Des 端口 http申请的端口 * @Author 小六六 * @Date 2020/10/13 11:42 * @Param * @Return */ int port; /** * @Des 构造方法 * @Author 小六六 * @Date 2020/10/13 11:42 * @Param * @Return */ public HttpServer(int port) { this.port = port; } /** * @Des 服务的启动办法 * @Author 小六六 * @Date 2020/10/13 11:43 * @Param * @Return */ public void start() throws Exception { //启动疏导类 ServerBootstrap bootstrap = new ServerBootstrap(); NioEventLoopGroup boss = new NioEventLoopGroup(); NioEventLoopGroup work = new NioEventLoopGroup(); bootstrap.group(boss, work) .handler(new LoggingHandler(LogLevel.DEBUG)) .channel(NioServerSocketChannel.class) .childHandler(new HttpServerInitializer()); ChannelFuture cf = bootstrap.bind(new InetSocketAddress(port)).sync(); System.out.println(" server start up on port : " + port); cf.channel().closeFuture().sync(); }}HttpServerInitializerpackage com.xiaoliuliu.six.finger.web.server;import io.netty.channel.ChannelHandler;import io.netty.channel.ChannelInitializer;import io.netty.channel.ChannelPipeline;import io.netty.channel.socket.SocketChannel;import io.netty.handler.codec.http.HttpObjectAggregator;import io.netty.handler.codec.http.HttpServerCodec;/** * @author 小六六 * @version 1.0 * @date 2020/10/13 11:57 * 用于配置 pipeline的解决链 */public class HttpServerInitializer extends ChannelInitializer<SocketChannel> { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline pipeline = socketChannel.pipeline(); // http 编解码 pipeline.addLast(new HttpServerCodec()); // http 音讯聚合器 pipeline.addLast("httpAggregator",new HttpObjectAggregator(512*1024)); // 申请处理器 pipeline.addLast(new HttpRequestHandler()); }}HttpRequestHandlerpackage com.xiaoliuliu.six.finger.web.server;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelFutureListener;import io.netty.channel.ChannelHandler;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import io.netty.handler.codec.http.*;import io.netty.util.AsciiString;import io.netty.util.CharsetUtil;import java.util.HashMap;import java.util.Map;import static io.netty.handler.codec.http.HttpUtil.is100ContinueExpected;/** * @author 小六六 * @version 1.0 * @date 2020/10/13 12:01 * 外围解决http申请的类,包含url的匹配外围办法都是在channelRead0办法 */public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> { private static final String FAVICON_ICO = "/favicon.ico"; private static final AsciiString CONNECTION = AsciiString.cached("Connection"); private static final AsciiString KEEP_ALIVE = AsciiString.cached("keep-alive"); @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); } @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { System.out.println("取得的参数:"+req); if (is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE)); } // 获取申请的uri String uri = req.uri(); Map<String,String> resMap = new HashMap<>(); resMap.put("method",req.method().name()); resMap.put("uri",uri); String msg = "<html><head><title>小六六揭示你</title></head><body>你申请uri为:" + uri+"</body></html>"; // 创立http响应 DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8)); //设置头信息 response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8"); //把音讯输入到浏览器 ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); }}ApplicationServer 测试类package com.xiaoliuliu.six.finger.web.demo.server;import com.xiaoliuliu.six.finger.web.server.HttpServer;/** * @author 小六六 * @version 1.0 * @date 2020/10/13 14:26 * 这个类 用于 搭建Netty web服务器的测试类,只实用于搭建教程的第一篇文章 */public class ApplicationServer { public static void main(String[] args) throws Exception { HttpServer server = new HttpServer(8081);// 8081为启动端口 server.start(); }}测试后果在浏览器上输出 ...

October 14, 2020 · 2 min · jiezi

关于springboot:14SpringBootMybatisVue-实现商品模块的crud操作

筹备工作第一步 创立新module,名字为10-springboot-goods-vue.第二步 增加maven依赖并进行初步配置(拷贝即可)第三步 拷贝pojo,dao,service包中的所有接口和类.第四步 拷贝动态资源到static目录(例如vue.js,axios.min.js) 商品查问设计及实现创立GoodsController并定义相干办法,代码如下: package com.cy.pj.goods.controller;import com.cy.pj.goods.pojo.Goods;import com.cy.pj.goods.service.GoodsService;import java.util.List;@RestControllerpublic class GoodsController { @Autowired private GoodsService goodsService; /**查问所有商品信息*/ @GetMapping("/goods/doFindGoods") public List<Goods> doFindGoods(){ return goodsService.findGoods(); }}在我的项目static目录创立goods-vue.html,并基于vue出现数据,代码如下 <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <div id="app"> <h1>The Goods Page</h1> <table> <thead> <tr> <th>id</th> <th>name</th> <th>remark</th> <th>createdTime</th> </tr> </thead> <tbody> <tr v-for="g in goods"> <td>{{g.id}}</td> <td>{{g.name}}</td> <td>{{g.remark}}</td> <td>{{g.createdTime}}</td> </tr> </tbody> </table> </div> <script src="js/axios.min.js"></script> <script src="js/vue.js"></script> <script> var vm=new Vue({//vue对象时vue.js利用的入口对象 el:"#app",//vue对象要监控的区域 data:{//此对象用于同步页面数据的一个对象 goods:{} }, methods:{//同步与页面元素事件处理函数 doFindGoods:function(){ let url="goods/doFindGoods"; axios.get(url) .then(function(result){ this.vm.goods=result.data; }); } }, mounted:function(){ this.doFindGoods(); } }); </script></body></html>启动tomcat进行拜访测试,如图所示: ...

October 14, 2020 · 1 min · jiezi

关于springboot:SpringBoot整合MyBatis框架的错误题集

1.NoUniqueBeanDefinitionException2.NullpointerException(空指针异样) 3.NoSuchBeanDefinition 4.SAXParseException(XML解析异样) 5.BindingException 6.参数绑定异样 7.No Test 8.测试类地位写错 9.HikariCP 常见问题剖析

October 14, 2020 · 1 min · jiezi

关于springboot:个人学习系列-Spring-Boot-集成-JApiDocs生成接口文档

之前应用Swagger来生成在线的接口文档,可是须要在代码中写入过多的注解,是在是麻烦。于是乎就找到JApiDocs来生成文档试试。。。1. 新建Spring Boot我的项目1.1 pom.xml<dependency> <groupId>io.github.yedaxia</groupId> <artifactId>japidocs</artifactId> <version>1.4.3</version></dependency>1.2 新建SysUser实体类/** * 实体类 * @author zhouzhaodong */@Datapublic class SysUser { /** * id */ private Integer id; /** * 姓名 */ private String name; /** * 明码 */ private String password; /** * 地址 */ private String address; /** * 测试字段 * @Ignore 该注解在生成文档的时候会被疏忽掉 */ @Ignore private String balabala;}1.3 这里我就不写service实现,间接写controller/** * 用户治理 * @author zhouzhaodong */@RestControllerpublic class SysUserController { /** * 依据用户id获取用户信息 * @param id * @return */ @RequestMapping("/getSysUser") public SysUser getSysUser(Integer id){ SysUser sysUser = new SysUser(); sysUser.setId(id); sysUser.setName("address"); sysUser.setPassword("12345"); sysUser.setAddress("青岛"); return sysUser; } /** * 测试接口 * @Ignore 该注解在生成文档的时候会被疏忽掉 * @param id * @return */ @Ignore @RequestMapping("/getOne") public SysUser getOne(Integer id){ return null; }}1.4 JApiDocsConfig文档生成/** * 文档生成 * @author zhouzhaodong */public class JapidocsConfig { public static void main(String[] args) { DocsConfig config = new DocsConfig(); // 我的项目根目录 config.setProjectPath("D:\\work\\workSpace\\springboot\\spring-boot-japidocs"); // 项目名称 config.setProjectName("springbootjapidocs"); // 申明该API的版本 config.setApiVersion("V1.0"); // 生成API 文档所在目录 config.setDocsPath("D:\\"); // 配置主动生成 config.setAutoGenerate(Boolean.TRUE); // 执行生成文档 Docs.buildHtmlDocs(config); }}1.5 运行生成接口文档控制台打印: ...

October 13, 2020 · 1 min · jiezi

关于springboot:spring-boot-集成-swagger-30-指南

时隔2年,swagger终于在社区推动下迎来了2.9版本之后的大版本升级:v3.0swagger 3.0 release notes3.0版本在配置上与2.9稍有差异,包含依赖包改为: springfox-boot-starter,启用注解更改为: @EnableOpenApi等。 具体应用步骤:1. 引入依赖springfox-boot-starter:以maven为例: <!-- 引入Swagger3依赖 --><dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version></dependency>2. 自定义配置信息/*** Swagger配置类*/@Configuration@EnableOpenApipublic class SwaggerConfig { @Bean public Docket docket(){ return new Docket(DocumentationType.OAS_30) .apiInfo(apiInfo()).enable(true) .select() //apis: 增加swagger接口提取范畴 .apis(RequestHandlerSelectors.basePackage("com.example")) //.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("XX我的项目接口文档") .description("XX我的项目形容") .contact(new Contact("作者", "作者URL", "作者Email")) .version("1.0") .build(); }}3. 在你的Controller上增加swagger注解以下为依赖diboot-core为例: @Api(tags="用户治理")@RestController@RequestMapping("/user")public class UserController { @ApiOperation("用户列表") @GetMapping("/{id}") public JsonResult getViewObjectMapping(@PathVariable("id") Long id) throws Exception{ return super.getViewObject(id, UserVO.class); } ...}4. 如启用了拜访权限,还需将swagger相干uri容许匿名拜访具体须要增加的uri有: ...

October 13, 2020 · 1 min · jiezi

关于springboot:个人学习系列-Spring-Boot-使用-jasypt-进行加密操作

写我的项目的时候总是会胆怯本人的数据库连贯信息泄露,所以记录一下加密的办法。jasypt加密1. 引入Maven依赖<dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>3.0.3</version></dependency>2. application.yml# 加密的密钥jasypt: encryptor: password: zhouzhaodong3. 生成加密后的密钥/** * 明码解码器主动注入 */ @Autowired StringEncryptor encryptor; @Test void test(){ String url = encryptor.encrypt("地址"); String name = encryptor.encrypt("用户名"); String password = encryptor.encrypt("明码"); System.out.println(url); System.out.println(name); System.out.println(password); }4. 对原数据进行替换即可spring: # 数据库连贯信息 datasource: # 数据库地址 url: ENC(url生成的密钥) # 用户名 username: ENC(用户名生成的密钥) # 明码 password: ENC(明码生成的密钥)集体博客地址:http://www.zhouzhaodong.xyz/

October 13, 2020 · 1 min · jiezi

关于springboot:07SpringBootMyBatisSpring-技术整合实现商品模块的CRUD操作补充笔记

业务形容基于Spring,MyBatis,SpringBoot,Thymeleaf技术实现商品模块的增删改查操作。 我的项目环境初始化筹备工作1. MySQL(5.7)2. JDK (1.8)3. Maven (3.6.3)4. STS(4.7.1)数据库初始化关上mysql控制台,而后按如下步骤执行goods.sql第一步:登录mysql mysql -uroot -proot第二步:设置控制台编码方式 set names utf8第三步:执行goods.sql文件(切记不要关上文件复制到mysql客户端运行) source d:/sqlspace/goods.sql其中goods.sql文件内容如下: drop database if exists dbgoods;create database dbgoods default character set utf8;use dbgoods;create table tb_goods( id bigint primary key auto_increment, name varchar(100) not null, remark text, createdTime datetime not null)engine=InnoDB;insert into tb_goods values (null,'java','very good',now());insert into tb_goods values (null,'mysql','RDBMS',now());insert into tb_goods values (null,'Oracle','RDBMS',now());insert into tb_goods values (null,'java','very good',now());insert into tb_goods values (null,'mysql','RDBMS',now());insert into tb_goods values (null,'Oracle','RDBMS',now());insert into tb_goods values (null,'java','very good',now());创立我的项目并增加依赖基于STS创立第一步:基于start.spring.io创立我的项目并设置根本信息第二步:创立我的项目时指定我的项目外围依赖第三步:我的项目创立当前剖析其构造 ...

October 12, 2020 · 1 min · jiezi

关于springboot:SpringBoot项目实践过程中遇到过哪些问题

SpringBoot 常见问题剖析 HikariCP 常见问题剖析 MyBatis常见问题剖析 Spring 常见问题剖析 thymeleaf 常见问题剖析 Ajax 常见问题剖析 Summary本大节次要心愿进步同学们对问题的思考,剖析以及解决问题的能力,并对问题进行总结,积淀,造成教训和习惯。

October 12, 2020 · 1 min · jiezi

关于springboot:12SpringBoot-工程中的响应标准设计及实现

背景剖析在基于C/S架构的编程模型中,客户端往往须要对服务端返回的数据,基于状态的不同进行不同的解决。例如,正确的状态数据一种出现形式,谬误的状态数据是另外一种出现形式。于是服务端响应数据的标准化设计油然而生。 响应规范设计在响应数据标准化设计时,首先要对响应数据进行剖析,哪些数据要响应到客户端,对这些数据进行怎么的状态设计等。如果当初响应的业务数据蕴含三局部:状态,音讯,具体数据。咱们能够这样设计,例如: package com.cy.pj.common.pojo;/** * 基于此对象封装服务端响应到客户端的数据 */public class ResponseResult { /**响应状态码(有的人用code)*/ private Integer state=1;//1示意ok,0示意error,..... /**状态码对应的信息*/ private String message="ok"; /**正确的响应数据*/ private Object data; public ResponseResult(){} public ResponseResult(String message){//new ResponseResult("delete ok"), this.message=message; } public ResponseResult(Object data){//new ResponseResult(list); this.data=data; } public ResponseResult(Throwable e){//new ResponseResult(e); this.state=0; this.message=e.getMessage(); } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Object getData() { return data; } public void setData(Object data) { this.data = data; }}响应数据的封装在Controller类的逻辑办法中进行失常的响应数据封装,例如: ...

October 12, 2020 · 1 min · jiezi

关于springboot:11SpringBoot-工程中的异常处理方式

背景剖析在我的项目的开发中,不论是对底层的数据逻辑操作过程,还是业务逻辑的处理过程,还是管制逻辑的处理过程,都不可避免会遇到各种可预知的、不可预知的异样。解决好异样对系统有很好的爱护作用,同时会大大提高用户的体验。 异样解决剖析概述Java我的项目中解决异样形式无非两种,要么执行trycatch操作,要么执行throw操作(抛给其它对象解决),无论采纳哪种形式,其目标是让咱们的系统对异样要有反馈。但当初的问题是咱们如何让这种反馈代码的编写即简略又直观、敌对。 解决标准咱们在解决异样的过程中通常要遵循肯定的设计规范,例如: 捕捉异样时与抛出的异样必须齐全匹配,或者捕捉异样是抛出异样的父类类型。防止间接抛出RuntimeException,更不容许抛出Exception或者Throwable,应应用有业务含意的自定义异样(例如ServiceException)。捕捉异样后必须进行解决(例如记录日志)。如果不想解决它,须要将异样抛给它的调用者。最外层的逻辑必须解决异样,将其转化成用户能够了解的内容。避免出现反复的代码(Don’t Repeat Yourself),即DAY准则。SpringBoot 工程下的异样解决筹备工作第一步:创立我的项目或module,并增加web依赖,代码如下: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>第二步:批改我的项目拜访端口为80,例如 server.port=80第三步:定义Controller类,代码如下: package com.cy.pj.arithmetic.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controllerpublic class ArithmeticController { @RequestMapping("doCompute/{n1}/{n2}") @ResponseBody public String doCompute(@PathVariable Integer n1, @PathVariable Integer n2){ Integer result=n1/n2; return "Result is "+result; }}第四步启动我的项目进行拜访测试 在浏览器地址栏输出http://localhost/doCompute/10/2,检测输入后果。 Result is 5默认异样解决在浏览器地址栏输出http://localhost/doCompute/10/0,检测输入后果。 对于这样的默认异样解决(spring boot提供),用户体验不太敌对,为了出现更加敌对的异样信息,咱们通常要对异样进行自定义解决。 本人try异样解决在管制层办法中,咱们能够进行try catch解决,例如: @RequestMapping("doCompute/{n1}/{n2}") @ResponseBody public String doCompute(@PathVariable Integer n1, @PathVariable Integer n2){ try{ Integer result=n1/n2; return "Result is "+result; }catch(ArithmeticException e){ return "exception is "+e.getMessage(); } } 一个Controller类中通常会有多个办法,这样多个办法中都写try语句进行异样解决会带来大量反复代码的编写,不易保护。 ...

October 12, 2020 · 1 min · jiezi

关于springboot:10SpringBoot-工程的健康监控实现

衰弱监控简述Spring Boot 中actuator模块提供了健康检查,审计、指标收集,HTTP跟踪等性能,能够帮忙咱们更好的治理和跟踪springboot我的项目。 衰弱监控配置实现在须要应用衰弱监控的我的项目或module中,增加如下依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId></dependency>增加完依赖当前,reload我的项目或module。 衰弱监控启动剖析启动我的项目,在浏览器中输出如下地址:(SpringBoot默认关上的监控选项无限) http://localhost/actuator其拜访后果,如图所示: 还能够在actuator列出的选中中进行点击,例如拜访health http://localhost/actuator/health其出现后果,如图所示(其中up状态示意失常): 如果心愿查看更多actuator选项,能够在spring boot中配置文件 application.properties中增加如下语句: management.endpoints.web.exposure.include=***而后,重启服务器,基于拜访http://localhost/actuator地址...) 总结(Summary)本大节次要是对springboot工程中的衰弱监控性能做了一个繁难剖析和实现,本人能够基于业务的须要,进行监控的配置和剖析.

October 12, 2020 · 1 min · jiezi

关于springboot:09springboot工程中的热部署实现

热部署简介Spring Boot 开发者为Spring Boot我的项目中提供了一个热部署(spring-boot-devtools)模块,反对我的项目的热部署(批改了某些资源当前无需重启服务),以进步开发效率.其底层其实是借助了两个类加载器做了具体实现,一个类加载器加载不变class,一个类加载器加载可能变动类,以提供类的热部署性能. 热部署环境初始化本次热部署的演示在IDEA开发中进行实现,其它工具能够本人通过搜索引擎进行学习。 IDEA 启动主动编译,如图所示: IDEA工具中启动注册窗口(按ctrl+shift+alt+/),如图所示: 抉择编译构建配置,如图所示: 热部署在我的项目中利用在须要热部署的我的项目或module中增加如下依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope></dependency>依赖下载当前,可重启reload我的项目,而后当咱们批改了src/main/java目录下的java文件或批改了src/main/resources目录下的配置文件时,默认都会重启你的web服务器,然而批改了测试类或html文件不会主动重启和部署。 总结(summary)本大节对springboot工程中的热部署进行了剖析和实现,能够idea工具中实际整个过程。

October 12, 2020 · 1 min · jiezi

关于springboot:08springboot-工程下lombok的应用

背景剖析在理论的java我的项目中咱们创立的所有pojo类简直都要为属性增加set/get/toString等相干办法,所有的日志记录相干类可能都要创立日志等对象,这些样板代码既没有技术含量,又影响着代码的好看,同时反复的编码过程会在无形中加大咱们的工作量。 此时Lombok应运而生。 lombok简介概述Lombok是一个第三的Java库,它会主动插入编辑器和构建工具中,Lombok提供了一组有用的正文,用来通知编译过程中的编译工具,在源代码编译成字节码的过程中,在字节码中增加一些量样板代码。 罕用注解剖析@Setter 用于为形容的类生成setter办法,不蕴含final润饰属性。@Getter 用于为形容的类生成getter办法。@ToString 用于为形容的类增加toString办法。@EqualsAndHashCode 用于为形容的类,生成hashCode和equals办法。@NoArgsConstructor 用于为形容的类生成无参的构造方法。@AllArgsConstructor 用于为形容的类生成蕴含类中所有字段的构造方法。@Data用于为形容的类生成setter/getter、equals、canEqual、hashCode、toString办法,如为final属性,则不会为该属性生成setter办法。@Slf4J 用于为形容的类增加一个日志属性对象。lombok装置idea中的装置配置第一步:关上idea的设置窗口,找到plugins菜单,搜寻lombok进行装置,如图所示: 第二步:启动注解解决,如图所示: 第三步:重启idea(可选,有的idea版本须要)。 sts中的装置配置本人百度尝试。 lombok在maven我的项目中利用第一步:增加lombok依赖。 <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>annotationProcessor</scope></dependency>第二步:在类上利用lombok注解。 @Data @NoArgsConstructor @AllArgsConstructor public class Goods { private Long id; private String name; private String remark; private Date createdTime;}第三步:编写单元测试类检测Lombok注解利用 @Slf4j@SpringBootTestpublic class GoodsTests{ @Test void testGoods(){ Goods g=new Goods(); g.setId(100L); g.setName("Lombok"); log.info("id的值为{}",g.getId()); log.info("name的值为{}",g.getName()); }}总结(Summary)本大节次要对lombok做了一个剖析,装置和配置,并结合实际我的项目解说了lombok的利用场景及具体利用过程。

October 12, 2020 · 1 min · jiezi

关于springboot:07SpringBootMyBatisSpring-技术整合实现商品模块的CRUD操作

业务形容基于Spring,MyBatis,SpringBoot,Thymeleaf技术实现商品模块的增删改查操作。 我的项目环境初始化筹备工作1. MySQL(5.7)2. JDK (1.8)3. Maven (3.6.3)4. STS(4.7.1)数据库初始化关上mysql控制台,而后按如下步骤执行goods.sql文件。第一步:登录mysql。 mysql –uroot –proot第二步:设置控制台编码方式。 set names utf8;第三步:执行goods.sql文件(切记不要关上文件复制到mysql客户端运行)。 source d:/goods.sql其中goods.sql文件内容如下: drop database if exists dbgoods;create database dbgoods default character set utf8;use dbgoods;create table tb_goods( id bigint primary key auto_increment, name varchar(100) not null, remark text, createdTime datetime not null)engine=InnoDB;insert into tb_goods values (null,'java','very good',now());insert into tb_goods values (null,'mysql','RDBMS',now());insert into tb_goods values (null,'Oracle','RDBMS',now());insert into tb_goods values (null,'java','very good',now());insert into tb_goods values (null,'mysql','RDBMS',now());insert into tb_goods values (null,'Oracle','RDBMS',now());insert into tb_goods values (null,'java','very good',now());创立我的项目并增加依赖基于STS创立第一步:基于start.spring.io 创立我的项目并设置根本信息 ...

October 12, 2020 · 3 min · jiezi

关于springboot:06SpringBoot工程下Spring-MVC技术的应用

Spring MVC 简介背景剖析在大型软件系统设计时,业务个别会绝对简单,如果所有业务实现的代码都纠缠在一起,会呈现逻辑不清晰、可读性差,保护艰难,改变一处就牵一发而动全身等问题。为了更好解决这个问题就有了咱们当初常说的分层架构设计。 MVC 是什么MVC是一种软件架构设计思维,基于MVC架构将咱们的应用软件进行分层设计和实现,例如能够分为视图层(View),管制层(Controller),模型层(Model),通过这样的分层设计让咱们程序具备更好的灵活性和可可扩展性.因为这样能够将一个简单应用程序进行简化,实现各司其职,各尽所能.比拟适宜一个大型利用的开发. Spring MVC 概述Spring MVC是MVC设计思维在Spring框架中的一种实现,基于这样的思维spring框架设计了一些相干对象,用于更好的基于MVC架构解决申请和响应,其繁难架构如图所示: 其中:1)DispatcherServlet是客户端所有申请解决的入口,负责申请转发。2)RequestMapping负责存储申请url到后端handler对象之间的映射。3)Handler 用于解决DispatcherServlet对象转发过去的申请数据。4)ViewResolver负责解决所有Handler对象响应后果中的view。 Spring MVC 疾速入门筹备工作第一步:创立我的项目module,根本信息如图所示: 第二步:增加我的项目依赖(能够在module创立时,也能够创立后),代码如下: Spring Web 依赖(提供了spring mvc反对并且会嵌入一个tomcat) <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>Thymeleaf 依赖(提供了以html作为页面模板进行解析和操作的相干对象) <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>第三步:启动我的项目检测控制台启动状态是否OK statics 目录剖析及利用statics 目录为springboot工程创立时增加了web依赖当前主动创立的目录,此目录中能够存储html、css、js、html等相干资源,这些资源能够在启动服务器当前,间接在浏览器进行拜访。例如:第一步:在statics目录下创立一个index.html页面,代码如下: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <h1>The First Html Page</h1></body></html>第二步:启动服务器并间接进行拜访测试,如图所示 templates 目录剖析及利用templates 目录为springboot工程创立时增加了thymeleaf依赖当前主动创立的目录,此目录中要存储一些html模板,这个模板页面不能间接通过浏览器url进行拜访,须要基于后端控制器,在办法中定义页面响应,例如: 第一步:定义TemplateController及办法,代码如下: package com.cy.pj.health.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class TemplateController { @RequestMapping("doTemplateUI") public String doTemplateUI(){ return "default"; }}第二步:在templates目录中定义模板页面default.html,代码如下: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <h1>The Default Template page</h1></body></html>其中,如果default.html要在放在templates子目录中,则还须要在配置文件中配置thymeleaf的前缀,例如: ...

October 12, 2020 · 2 min · jiezi

关于springboot:05SpringBoot工程中的MyBatis框架的整合实现及原理分析

整合MyBatis的初步剖析概述Mybatis是一个优良的长久层框架,底层基于JDBC实现与数据库的交互。并在JDBC操作的根底上做了封装和优化,它借助灵便的SQL定制,参数及后果集的映射形式,更好的适应了以后互联网技术的倒退。Mybatis框架的简略利用架构如图所示:在当今的互联网利用中我的项目,mybatis框架通常会由spring框架进行资源整合,作为数据层技术实现数据交互操作。 筹备工作第一步:创立我的项目module,例如: 第二步:增加依赖 mysql 驱动依赖 <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope></dependency>spring jdbc 依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId></dependency>mybatis starter依赖 <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version></dependency> 第二步:application.properties 配置文件中增加繁难配置 连接池配置 spring.datasource.url=jdbc:mysql:///dbgoods?serverTimezone=GMT%2B8&characterEncoding=utf8spring.datasource.username=rootspring.datasource.password=rootmybatis配置 mybatis.mapper-locations=classpath:/mapper/*/*.xml环境测试代码实现在src/test/java目录中增加测试类,对mybatis框架整合进行根本测试,代码如下: package com.cy.pj.goods.dao;import java.sql.Connection;import org.apache.ibatis.session.SqlSession;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;@SpringBootTestpublic class MyBatisTests { @Autowired private SqlSession sqlSession; @Test public void testGetConnection() { Connection conn=sqlSession.getConnection(); System.out.println("connection="+conn); }}在SpringBoot脚手架工程中,Spring框架会基于MyBatis框架底层配置,创立SqlSessionFactory对象,而后再通过此工厂对象创立SqlSession,最初基于Springku框架为测试类注入SqlSession对象,接下来,咱们能够通过SqlSession对象实现与数据库的会话了。 整合MyBatis业务代码实现及原理剖析业务形容基于SpringBoot脚手架工程对MyBatis框架的整合,实现对商品库中商品数据的查问业务。 API架构设计 业务时序图剖析 业务代码设计及实现第一步:定义商品模块POJO对象类型(基于此对象存储商品数据),代码如下: package com.cy.pj.goods.pojo;import java.util.Date;/**用于存储商品信息的pojo对象*/public class Goods { private Long id; private String name; private String remark; private Date createdTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Date getCreatedTime() { return createdTime; } public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; }}第二步:定义商品模块长久层对象GoodsDao接口及办法映射,代码如下 ...

October 12, 2020 · 2 min · jiezi

关于springboot:04SpringBoot工程下如何实现对HikariCP连接池的整合

池化思维剖析池化思维是咱们我的项目开发过程中的一种十分重要的思维,如整数池,字符串池,对象池、连接池、线程池等都是池化思维的一种利用,都是通过复用对象,以缩小因创立和开释对象所带来的资源耗费,进而来晋升零碎性能。例如Integer对象的外部池利用,代码如下: package com.cy.java.pool;public class TestInteger01 { public static void main(String[] args) { Integer n1=100;//Integer.valueOf(100) 编译时优化 Integer n2=100; Integer n3=200; Integer n4=200;//池中没有则new Integer(200) System.out.println(n1==n2);//true System.out.println(n3==n4);//false } }数据库连接池简介背景剖析目开发过程中应用程序与数据库交互时,“取得连贯”或“开释连贯”是十分耗费系统资源的两个过程,频繁地进行数据库连贯的建设和敞开会极大影响零碎的性能,若多线程并发量很大,这样耗时的数据库连贯就可能让零碎变得卡顿。因为TCP连贯的创立开销非常低廉,并且数据库所能承载的TCP并发连接数也有限度,针对这种场景,数据库连接池应运而生。如下图所示: 思考:如果当初是让你去设计一个连接池,你会从什么角度进行设计?第一:物理存储构造(基于什么构造去存储数据)第二:基于什么算法从池中取连贯?第三:基于什么算法从池中移除连贯?第四:当池中没有连贯时,基于什么形式解决连贯申请?第五:池是能够共享,咱们须要思考池在拜访的时并发平安? 连接池原理剖析在零碎初始化的时候,在内存中开拓一片空间,将肯定数量的数据库连贯作为对象存储在对象池里,并对外提供数据库连贯的获取和偿还办法。用户拜访数据库时,并不是建设一个新的连贯,而是从数据库连接池中取出一个已有的闲暇连贯对象;应用结束偿还后的连贯也不会马上敞开,而是由数据库连接池对立治理回收,为下一次借用做好筹备。如果因为高并发申请导致数据库连接池中的连贯被借用结束,其余线程就会期待,直到有连贯被偿还。整个过程中,连贯并不会敞开,而是源源不断地循环应用,有借有还。数据库连接池还能够通过设置其参数来管制连接池中的初始连接数、连贯的上上限数,以及每个连贯的最大应用次数、最大闲暇工夫等,也能够通过其本身的管理机制来监督数据库连贯的数量、应用状况等。 Java中的连接池Java官网,为了在应用程序中更好的利用连接池技术,定义了一套数据源标准,例如javax.sql.DataSource接口,基于这个接口,很多团队或集体创立了不同的连接池对象。而后咱们的应用程序中通过耦合与DataSource接口,便能够不便的切换不同厂商的连接池。Java我的项目中通过连接池获取连贯的一个根本过程,如下图所示: 在上图中,用户通过DataSource对象的getConnection()办法,获取一个连贯。如果池中有连贯,则间接将连贯返回给用户。如果池中没有连贯,则会调用Dirver(驱动,由数据库厂商进行实现)对象的connect办法从数据库获取,拿到连贯当前,能够将连贯在池中放一份,而后将连贯返回给调用方。连贯需求方再次须要连贯时,能够从池中获取,用完当前再还给池对象。 数据库连接池在Java数据库相干中间件产品群中,应该算是底层最根底的一类产品,作为企业应用开发必不可少的组件,有数蠢才们为咱们奉献了一个又一个的优良产品,它们有的随时代倒退,功成身退,有的则还在一直迭代,老而弥坚,更有新生代产品,或性能无敌,或性能全面。目前市场上常见的连接池有DBCP、C3P0,DRUID,HikariCP等。SpringBoot工程下HikariCP整合测试数据初始化关上mysql控制台,而后按如下步骤执行goods.sql文件。第一步:登录mysql。 mysql –uroot –proot第二步:设置控制台编码方式。 set names utf8;第三步:执行goods.sql文件(切记不要关上文件复制到mysql客户端运行)。 source d:/goods.sql其中goods.sql文件内容如下: drop database if exists dbgoods;create database dbgoods default character set utf8;use dbgoods;create table tb_goods( id bigint primary key auto_increment, name varchar(100) not null, remark text, createdTime datetime not null)engine=InnoDB;insert into tb_goods values (null,'java','very good',now());insert into tb_goods values (null,'mysql','RDBMS',now());insert into tb_goods values (null,'Oracle','RDBMS',now());insert into tb_goods values (null,'java','very good',now());insert into tb_goods values (null,'mysql','RDBMS',now());insert into tb_goods values (null,'Oracle','RDBMS',now());insert into tb_goods values (null,'java','very good',now());创立我的项目Module并增加相干依赖第一步:基于IDEA创立我的项目Module,如图所示: ...

October 12, 2020 · 2 min · jiezi

关于springboot:03基于IDEA创建SpringBoot项目并进行入门分析

SpringBoot 我的项目创立创立Module基于IDEA创立我的项目Module,模块名为04-springboot-start,组id和包名为com.cy,如图所示:填写module信息,如图所示:抉择我的项目module版本,临时不须要本人手动增加任何依赖,如图所示:填写Module名称,实现module创立,如图所示 我的项目构造剖析我的项目Module创立好当前,其代码构造剖析,如图所示: SpringBoot 我的项目启动剖析启动入口SpringBoot 工程中由SpringBootApplication注解形容的类为启动入口类,例如: package com.cy;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class Application {//Application.class public static void main(String[] args) {//Main Thread SpringApplication.run(Application.class, args); }}启动过程概要剖析SpringBoot工程启动时其繁难初始化过程,如图所示: 在启动过程中底层做了哪些事件,大抵形容如下:1)基于配置加载类(通过ClassLoader将指定地位的类读到内存->底层通过线程调用IO从磁盘读取到内存)。2)对类进行剖析(创立字节码对象-Class类型,通过反射获取器配置信息)。3)对于指定配置(例如由spring特定注解形容)的对象存储其配置信息(借助BeanDefinition对象存储)。4)基于BeanDefinition对象中class的配置构建类的实例(Bean对象),从进行bean对象的治理。 SpringBoot 疾速入门剖析业务形容在我的项目Module中定义一个类,类名为DefaultCache,而后将此类对象交给Spring创立并治理。最初通过单元测试对类的实例进行剖析。 API设计剖析基于业务形容,进行API及关系设计,如图所示: 代码编写及运行基于业务及API设计,进行代码编写,其过程如下: 第一步:定义DefaultCache类 package com.cy.pj.common.cache;import org.springframework.stereotype.Component;/** * @Component 注解形容的类,示意此类交给Spring框架治理。 */@Componentpublic class DefaultCache {}第二步:定义DefaultCacheTests单元测试类 package com.cy.pj.common.cache;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;public class DefaultCacheTests { /** * @Autowired 注解形容的属性由spring框架依照肯定规定为其注入值(赋值) * 赋值过程是怎么的? * 1)依赖查找?(请问查找规定是什么?) * 2)依赖注入?(须要借助什么技术?) */ @Autowired private DefaultCache defaultCache; @Test void testDefaultCache(){ System.out.println(defaultCache.toString()); //FAQ? defaultCache变量援用的对象是由谁创立的,存储到了哪里?bean pool }}第三步:运行单元测试类进行利用剖析启动运行单元测试办法,检测其输入后果,基于后果剖析:1)SpringBoot我的项目中Bean对象的构建。2)SpringBoot我的项目中Bean对象的获取。 ...

October 12, 2020 · 1 min · jiezi

关于springboot:02如何基于STS实现SpringBoot-工程项目的创建

SpringBoot我的项目环境初始化本次我的项目的创立,须要如下软件已筹备并已实现其配置. 下载、装置、配置JDK(这里抉择JDK8版本)。下载、解压、配置maven(这里抉择3.6.3版本)下载、解压、配置STS(这里抉择4.7.1版本)阐明:对于环境下载,装置配置,本人通过官网或搜索引擎查问实现。 SpringBoot我的项目创立过程剖析及实现基于STS内置start创立第一步:关上sts软件,快捷键ctrl+n关上新建窗口,如图所示: 第二步:输出我的项目相干信息,如图所示: 第三步:抉择SpringBoot版本,如图所示: 第四步:我的项目构造展现,我的项目创立完当前的构造如下: 基于浏览器(Browser)创立第一步:关上浏览器输出start.spring.io,而后输出我的项目信息,进行我的项目构建,如图所示: 第二步:将构建并下载下来的我的项目进行解压,如图所示: 第三步:将解压好的我的项目导入到sts中,如图所示: 第四部步:我的项目构造展现,如图所示: 基于STS一般maven形式创立第一步:创立一般maven我的项目,快捷键ctrl+n 搜maven,如图所示: 第二步:抉择我的项目骨架,如图所示: 第三步:输出像我的项目信息,如图所示: 第四步:我的项目构造展现,如图所示: 第五步:将已有我的项目的pom文件,我的项目启动类,配置文件拷贝到maven工程中,并进行适当批改,例如批改一下pom文件中项目名称.SpringBoot我的项目创立过程问题剖析JDK装置配置问题本地装置的JDK短少资源,如图所示: Maven配置及更新问题Maven的配置文件谬误,如图所示: Maven中不能有多个私服镜像,如图所示 Maven我的项目依赖下载更新问题 网络连接(Connect)问题spring 官网服务器连贯超时. 总结(Summary)本大节重点解说了基于STS工具创立和导入SpringBoot工程的几种形式以及在实际过程的一些问题的思考和解决方案。

October 12, 2020 · 1 min · jiezi

关于springboot:Ajax技术运用

什么是Ajax?Ajax (Asynchronous JavaScript and XML) 是一种Web利用技术,能够借助客户端脚本(javascript)与服务端利用进行异步通信,获取服务端数据当前,能够进行部分刷新。进而进步数据的响应和渲染速度。 传统Web利用中繁难的同步模型剖析基于Ajax技术的异步申请响应模型剖析 做一个入门的Demo首先关上百度的首页,再控制台编码。 var xhr=new XMLHttpRequest(); //第一步:创立XMLHttpRequest对象xhr.onreadystatechange=function(){ //第二步:如果状态扭转,将触发这个函数 if(xhr.readyState==4&&xhr.status==200){ //状态有0 1 2 3 4 五种,返回数据胜利的状态为200 console.log(xhr.responseText); //在控制台打印返回的数据 }}xhr.open("GET","https://www.baidu.com",true); //第三步:创立连贯xhr.send(null); //第四步:发送申请,GET形式的申请,参数能够为null申请后果展现: 基于SpringBoot我的项目下试验设置端口 server.port=80当xhr.open()函数的最初的参数为false时,启动的是main线程,不举荐应用main线程,参数个别都是应用true

October 12, 2020 · 1 min · jiezi

关于springboot:springbootroute十三整合RabbitMQ

这篇是SpringBoot整合音讯队列的第一篇文章,咱们具体介绍下音讯队列的相干内容。 音讯队列简介1. 什么是音讯队列MQ(Message Quene):通过典型的生产者和消费者模型,生产者一直向音讯队列中产生音讯,消费者一直的从队列中获取音讯。因为生产者和消费者都是异步的,而且生产者只关怀音讯的发送,消费者只关怀音讯的接管,没有业务逻辑的侵入,轻松实现业务解耦。 2. 音讯队列有什么用异步解决场景形容:某商场具备注册性能,注册的时候须要发送短信验证码。 传统的做法是用户提交信息到用户服务,用户服务调用短信服务发送短信,而后给用户返回响应,这种是同步的解决形式,耗时较长。退出音讯队列后,用户间接提交信息到用户服务,将信息写入音讯队列,间接给用户返回响应,短信服务从音讯队列中读取音讯进行发送短信。 利用解耦场景形容:某商场下单流程。 传统做法是用户下单,订单零碎去查问库存零碎,如果库存零碎宕机了,则下单失败,损失订单量。退出音讯队列后,用户下单,订单零碎记录订单,将订单信息写入音讯队列,下单胜利,而后库存零碎恢复正常后去操作数据库库存(不思考库存为0的状况)。这样订单零碎和库存零碎就达到松耦合的目标了 流量削峰场景形容:秒杀流动。 流量过大必定会导致响应超时或零碎宕机,退出音讯队列,用户秒杀申请写入音讯队列,设置音讯队列的长度等属性,达到音讯队列最大长度后,间接返回秒杀失败,而后再去生产音讯队列的数据,实现秒杀。 RabbitMQ简介RabbitMQ是用Erlang语言编写的,实现了高级音讯队列协定(AMQP)的消息中间件。 1. AMQP协定概念AMQP:AMQP是一种链接协定,间接定义网络替换的数据格式,这使得实现了AMQP的provider自身就是跨平台的。以下是AMQP协定模型: server - 又称broker,接管客户端的链接,实现amqp实体服务。Connection - 链接,应用程序跟broker的网络链接。channel - 网络信道,简直所有的操作都是在channel中进行,数据的流转都要在channel上进行。channel是进行音讯读写的通道。客户端能够建设多个channel,每个channel代表一个会话工作。message - 音讯,服务器与应用程序之间传送的数据。由properties和body组成。properties能够对音讯进行润饰,比方音讯的降级,提早等高级个性。body就是音讯体的内容。virtual host - 虚拟主机,用于进行逻辑隔离,最上层的音讯路由,一个虚拟地址外面能够有多个交换机。exchange和音讯队列message quene。exchange - 交换机,接管音讯,依据路由器转发音讯到绑定的队列。binding - 绑定,交换机和队列之间的虚构链接,绑定中能够蕴含routing key。routing key - 一个路由规定,虚拟机能够用它来确定jiekyi如何路由一个特定音讯。quene - 音讯队列,保留音讯并将它们转发给消费者。2. RabbitMQ的音讯模型1. 简略模型 在上图中: p:生成者C:消费者红色局部:quene,音讯队列2. 工作模型 在上图中: p:生成者C1、C2:消费者红色局部:quene,音讯队列当音讯解决比拟耗时时,就会呈现生产音讯的速度远远大于生产音讯的速度,这样就会呈现音讯沉积,无奈及时处理。这时就能够让多个消费者绑定一个队列,去生产音讯,队列中的音讯一旦生产就会失落,因而工作不会反复执行。 3. 播送模型(fanout) 这种模型中生产者发送的音讯所有消费者都能够生产。 在上图中: p:生成者X:交换机C1、C2:消费者红色局部:quene,音讯队列4. 路由模型(routing) 这种模型消费者发送的音讯,不同类型的音讯能够由不同的消费者去生产。 在上图中: p:生成者X:交换机,接管到生产者的音讯后将音讯投递给与routing key齐全匹配的队列C1、C2:消费者红色局部:quene,音讯队列5. 订阅模型(topic) 这种模型和direct模型一样,都是能够依据routing key将音讯路由到不同的队列,只不过这种模型能够让队列绑定routing key 的时候应用通配符。这种类型的routing key都是由一个或多个单词组成,多个单词之间用.宰割。 通配符介绍: *:只匹配一个单词 #:匹配一个或多个单词 6. RPC模型 ...

October 12, 2020 · 2 min · jiezi

关于springboot:12SpringBoot-工程中的响应标准设计及实现

背景剖析在基于C/S架构的编程模型中,客户端往往须要对服务端返回的数据,基于状态的不同进行不同的解决。例如,正确的状态数据一种出现形式,谬误的状态数据是另外一种出现形式。于是服务端响应数据的标准化设计油然而生。 响应规范设计在响应数据标准化设计时,首先要对响应数据进行剖析,哪些数据要响应到客户端,对这些数据进行怎么的状态设计等。如果当初响应的业务数据蕴含三局部:状态,音讯,具体数据。咱们能够这样设计,例如: package com.cy.pj.common.pojo;/** * 基于此对象封装服务端响应到客户端的数据 */public class ResponseResult { /**响应状态码(有的人用code)*/ private Integer state=1;//1示意ok,0示意error,..... /**状态码对应的信息*/ private String message="ok"; /**正确的响应数据*/ private Object data; public ResponseResult(){} public ResponseResult(String message){//new ResponseResult("delete ok"), this.message=message; } public ResponseResult(Object data){//new ResponseResult(list); this.data=data; } public ResponseResult(Throwable e){//new ResponseResult(e); this.state=0; this.message=e.getMessage(); } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Object getData() { return data; } public void setData(Object data) { this.data = data; }}响应数据的封装在Controller类的逻辑办法中进行失常的响应数据封装,例如: ...

October 12, 2020 · 1 min · jiezi

关于springboot:11SpringBoot-工程中的异常处理方式

背景剖析在我的项目的开发中,不论是对底层的数据逻辑操作过程,还是业务逻辑的处理过程,还是管制逻辑的处理过程,都不可避免会遇到各种可预知的、不可预知的异样。解决好异样对系统有很好的爱护作用,同时会大大提高用户的体验。 异样解决剖析概述Java我的项目中解决异样形式无非两种,要么执行trycatch操作,要么执行throw操作(抛给其它对象解决),无论采纳哪种形式,其目标是让咱们的系统对异样要有反馈。但当初的问题是咱们如何让这种反馈代码的编写即简略又直观、敌对。 解决标准咱们在解决异样的过程中通常要遵循肯定的设计规范,例如: 捕捉异样时与抛出的异样必须齐全匹配,或者捕捉异样是抛出异样的父类类型。防止间接抛出RuntimeException,更不容许抛出Exception或者Throwable,应应用有业务含意的自定义异样(例如ServiceException)。捕捉异样后必须进行解决(例如记录日志)。如果不想解决它,须要将异样抛给它的调用者。最外层的逻辑必须解决异样,将其转化成用户能够了解的内容。避免出现反复的代码(Don’t Repeat Yourself),即DAY准则。SpringBoot 工程下的异样解决筹备工作第一步:创立我的项目或module,并增加web依赖,代码如下: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>第二步:批改我的项目拜访端口为80,例如 server.port=80第三步:定义Controller类,代码如下: package com.cy.pj.arithmetic.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controllerpublic class ArithmeticController { @RequestMapping("doCompute/{n1}/{n2}") @ResponseBody public String doCompute(@PathVariable Integer n1, @PathVariable Integer n2){ Integer result=n1/n2; return "Result is "+result; }}第四步启动我的项目进行拜访测试 在浏览器地址栏输出http://localhost/doCompute/10/2,检测输入后果。 Result is 5默认异样解决在浏览器地址栏输出http://localhost/doCompute/10/0,检测输入后果。 对于这样的默认异样解决(spring boot提供),用户体验不太敌对,为了出现更加敌对的异样信息,咱们通常要对异样进行自定义解决。 本人try异样解决在管制层办法中,咱们能够进行try catch解决,例如: @RequestMapping("doCompute/{n1}/{n2}") @ResponseBody public String doCompute(@PathVariable Integer n1, @PathVariable Integer n2){ try{ Integer result=n1/n2; return "Result is "+result; }catch(ArithmeticException e){ return "exception is "+e.getMessage(); } } 一个Controller类中通常会有多个办法,这样多个办法中都写try语句进行异样解决会带来大量反复代码的编写,不易保护。 ...

October 12, 2020 · 1 min · jiezi

关于springboot:九-SpringBoot起飞之路整合集成Swagger-2-And-3

趣味的敌人能够去理解一下其余几篇,你的赞就是对我最大的反对,感激大家! (一) SpringBoot腾飞之路-HelloWorld (二) SpringBoot腾飞之路-入门原理剖析 (三) SpringBoot腾飞之路-YAML配置小结(入门必知必会) (四) SpringBoot腾飞之路-动态资源解决 (五) SpringBoot腾飞之路-Thymeleaf模板引擎 (六) SpringBoot腾飞之路-整合JdbcTemplate-Druid-MyBatis (七) SpringBoot腾飞之路-整合SpringSecurity (八) SpringBoot腾飞之路-整合Shiro 阐明: 3.0 的版本没怎么用过,只是进行了简略的整合,或者会有一些不欠缺的中央,欢送大家交换分享SpringBoot 腾飞之路 系列文章的源码,均同步上传到 github 了,有须要的小伙伴,随便去 down https://github.com/ideal-20/S...一 初识 Swagger跳过铺垫,请间接翻越到 第二大点 ~ (一) 先谈谈前后端拆散在最早的 JavaWeb 时代的时候,如果想要返回一个页面,你须要一行一行的去 print,如果遇到变量,还须要本人进行字符串的拼接 Public class TestServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponseresp response) throws ServletException, IOException { String name = req.getParameter("name"); String age = req.getParameter("age"); PrintWriter out = resp.getWriter(); out.println("<html>"); out.println("<head><title>展现数据</title></head>"); out.println("<body>name:" + name + "<br/> age: " + age +"</body>"); out.println("</html>"); } }接着 JSP 就呈现了,其本质尽管还是一个 Servlet,不过编写一个 JSP 的形式和编写 HTML 的是基本一致的,然而 JSP 开始容许咱们在页面中通过 %% 引入 Java 代码,也就是说咱们能够通过在 JSP 页面中通过书写 Java 代码达到显示动静内容的成果,例如在 JSP 中定义方法、书写控制台输入语句等等,大部分你能想到的逻辑都能够在这里来做 ...

October 11, 2020 · 5 min · jiezi

关于springboot:京淘-day10

1.对于服务器检索指令1.1 检索java程序命令: jps 敞开过程: kill PID号 “低微的杀死过程” 如果以后的过程项被其余过程应用时 ,则不会敞开.kill -15 PID号 “温顺的杀死” 被杀死之前能够做善后kill -9 PID号 强制杀死1.2 检索任意程序命令: ps -ef | grep xxxx服务名称阐明: ps -ef 示意获取以后Linux零碎中的所有的服务信息. “|” 将管道之前的查问的后果当做参数传递给后边的操作.例子: 1.3 对于防火墙的阐明1). 查看防火墙凋谢的端口 `firewall-cmd --list-ports` 2).查看端口是否凋谢 `firewall-cmd --query-port 80/tcp` * 13). 开启防火墙 `firewall-cmd --zone=public --add-port=80/tcp --permanent` 4).移除端口 `firewall-cmd --zone=public --remove-port=9090/tcp --permanent` 5).对于防火墙操作的解释–zone #作用域 –add-port=80/tcp #增加端口,格局为:端口/通信协定 –remove-port=80/tcp #移除端口,格局为:端口/通信协定 –permanent #永恒失效,没有此参数重启后生效 6).重启防火墙 `firewall-cmd --reload` 2.Linux 装置Nginx服务器2.1 Linux我的项目部署图 2.2 Nginx 装置2.2.1 Linux下载nginx服务器 ...

October 11, 2020 · 2 min · jiezi

关于springboot:京淘-day09

1.配置虚拟机环境1.1 批改虚拟机网络空间设定net8网卡的IP网段设定DHCP设置.查看windowsIP地址 1.2 重启Linux虚拟机网卡命令: ip addr如果没有IP展示则执行如下的命令 `service NetworkManager stop chkconfig NetworkManager off 永恒敞开 Manager网卡service network restart 重启network网卡` * 1* 2* 3windows ping Linux Linux 我的项目部署============== 2.1 装置JDK2.1.1 上传JDK 2.1.2 解压JDK文件命令: tar -zxvf jdk-8u51-linux-x64.tar.gz解压实现之后,将文件目录整顿一下. 2.1.3 配置环境变量命令: `#设定jdk环境export JAVA_HOME=/usr/local/src/jdk1.8export PATH=$JAVA_HOME/bin:$PATHexport CLASSPATH=.:$JAVA_HOME/lib` 2).刷新环境变量 2.2 装置Linux数据库-mariadb2.2.1 查看网络链接 2.2.2 装置数据库具体方法:参见博客信息 装置数据MariaDB 2.3 部署tomcats服务器2.3.1 服务器部署图 2.3.2 装置数据库阐明:具体装置过程,参见博客信息. 2.3.3 近程链接Mysql数据库 2.3.4 批改图片配置文件阐明:因为windows的门路与Linux的门路不统一,所以必须筹备一个Linux的图片上传的根目录.所以须要将代码中的图片的配置文件进行批改. 2.3.4 打包公布阐明:将代码批改之后,进行打包,之后上传到指定的文件目录中发布命令:[root@localhost 09]# java -jar 8081.war & 作业熟练掌握 课上的命令 防火墙/网卡重启/数据库操作等回退镜像. 将明天的工作重新配置二遍.

October 11, 2020 · 1 min · jiezi

关于springboot:京淘-day08

文件上传优化========== 1.1 url优化阐明: 如果须要通过网络虚构门路拜访服务器.则应该依照如下的配置实现. 本地磁盘门路: D:JT-SOFTimages20200930a.jpg网络虚构门路: http://image.jt.com20200930a.jpg1.2 编辑pro配置文件 1.3 实现属性的动静赋值`package com.jt.service;import com.jt.vo.ImageVO;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.PropertySource;import org.springframework.stereotype.Service;import org.springframework.web.multipart.MultipartFile;import javax.imageio.ImageIO;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashSet;import java.util.Set;import java.util.UUID;@Service@PropertySource("classpath:/properties/images.properties") //容器动静加载指定的配置文件public class FileServiceImpl implements FileService{ //因为属性的值前期可能会发生变化,所以应该动静的获取属性数据. 利用pro配置文件 @Value("${image.rootDirPath}") private String rootDirPath; // = "D:/JT-SOFT/images"; @Value("${image.urlPath}") private String urlPath; // = "http://image.jt.com"; //1.2 筹备图片的汇合 蕴含了所有的图片类型. private static Set<String> imageTypeSet; static { imageTypeSet = new HashSet<>(); imageTypeSet.add(".jpg"); imageTypeSet.add(".png"); imageTypeSet.add(".gif"); } /** * 欠缺的校验的过程 * 1. 校验是否为图片 * 2. 校验是否为恶意程序 * 3. 避免文件数量太多,分目录存储. * 4. 避免文件重名 * 5. 实现文件上传. * @param uploadFile * @return */ @Override public ImageVO upload(MultipartFile uploadFile) { //0.避免有多余的空格 所以先做去空格的解决 rootDirPath.trim(); urlPath.trim(); //1.校验图片类型 jpg|png|gif..JPG|PNG.... //1.1 获取以后图片的名称 之后截取其中的类型. abc.jpg String fileName = uploadFile.getOriginalFilename(); int index = fileName.lastIndexOf("."); String fileType = fileName.substring(index); //将数据转化为小写 fileType = fileType.toLowerCase(); //1.3 判断图片类型是否正确. if(!imageTypeSet.contains(fileType)){ //图片类型不匹配 return ImageVO.fail(); } //2.校验是否为恶意程序 依据宽度/高度进行判断 try { //2.1 利用工具API对象 读取字节信息.获取图片对象类型 BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream()); //2.2 校验是否有宽度和高度 int width = bufferedImage.getWidth(); int height = bufferedImage.getHeight(); if(width==0 || height==0){ return ImageVO.fail(); } //3.分目录存储 yyyy/MM/dd 分隔 //3.1 将工夫依照指定的格局要求 转化为字符串. String dateDir = new SimpleDateFormat("/yyyy/MM/dd/") .format(new Date()); //3.2 拼接文件存储的目录对象 String fileDirPath = rootDirPath + dateDir; File dirFile = new File(fileDirPath); //3.3 动态创建目录 if(!dirFile.exists()){ dirFile.mkdirs(); } //4.避免文件重名 uuid.jpg 动静拼接 //4.1 动静生成uuid 实现文件名称拼接 名.后缀 String uuid = UUID.randomUUID().toString().replace("-", ""); String realFileName = uuid + fileType; //5 实现文件上传 //5.1 拼接文件实在门路 dir/文件名称. String realFilePath = fileDirPath + realFileName; //5.2 封装对象 实现上传 File realFile = new File(realFilePath); uploadFile.transferTo(realFile); //实现文件上传胜利!!! http://image.jt.com20200930a.jpg String url = urlPath + dateDir + realFileName; return ImageVO.success(url,width,height); } catch (IOException e) { e.printStackTrace(); return ImageVO.fail(); } }}` 2 反向代理机制阐明2.1 为什么须要反向代理需要:当实现文件上传时,业务返回页面的是虚拟地址门路url地址: http://image.jt.com/2020/09/30/a.jpg实在图片地址: file:///D:/JT-SOFT/image/2020/09/30/d534bed912c748b0ac979ee40222490a.jpg问题: 如何让用户通过url拜访 找到实在的磁盘地址的图片. ...

October 11, 2020 · 3 min · jiezi

关于springboot:10SpringBoot-工程的健康监控实现

衰弱监控简述Spring Boot 中actuator模块提供了健康检查,审计、指标收集,HTTP跟踪等性能,能够帮忙咱们更好的治理和跟踪springboot我的项目。 衰弱监控配置实现在须要应用衰弱监控的我的项目或module中,增加如下依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId></dependency>增加完依赖当前,reload我的项目或module。 衰弱监控启动剖析启动我的项目,在浏览器中输出如下地址:(SpringBoot默认关上的监控选项无限) http://localhost/actuator其拜访后果,如图所示: 还能够在actuator列出的选中中进行点击,例如拜访health http://localhost/actuator/health其出现后果,如图所示(其中up状态示意失常): 如果心愿查看更多actuator选项,能够在spring boot中配置文件 application.properties中增加如下语句: management.endpoints.web.exposure.include=***而后,重启服务器,基于拜访http://localhost/actuator地址... 总结(Summary)本大节次要是对springboot工程中的衰弱监控性能做了一个繁难剖析和实现,本人能够基于业务的须要,进行监控的配置和剖析.

October 10, 2020 · 1 min · jiezi

关于springboot:Spring-Boot优雅整合Swagger2自动生成在线文档

Spring Boot优雅整合Swagger2,主动生成在线文档日常求赞,感激老板。欢送关注公众号:其实是白羊。干货继续更新中...... 一、前言当初的很多我的项目都是前后端拆散的,后端提供接口,前端调用接口,在这个过程中个别后端会向前端提供一份接口文档,然而随着程序的调整,咱们还要一直的去迭代接口文档,最初可能会搞出一堆,写起来比拟耗时且在规范性上也很难要求。在这个前提下咱们能够抉择Swagger退出到咱们的我的项目中。 Swagger提供了很多的性能,其中Swagger UI和Swagger Inspector应用的比拟多 Swagger UI:提供了一个UI页面形容我的项目中的接口(包含接口含意、uri、办法、参数、返回值和字段含意等)Swagger Inspector:提供了在线对接口进行测试的性能二、集成Swagger咱们这里的我的项目框架是Spring Boot 1.引入依赖<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version></dependency><dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version></dependency>2.配置类/** * @Description swagger配置文件 * @Author ZhangLinlu * @Date 2020/10/10 **/@EnableSwagger2@Configurationpublic class SwaggerConfig { private ApiInfo apiInfo() { return new ApiInfoBuilder() // 设置页面题目 .title("应用swagger2构建后端api接口文档") // 设置联系人 .contact(new Contact("myname", "url", "email")) // 形容 .description("欢送拜访后端接口文档,这里是形容信息") // 定义版本号 .version("1.0").build(); } @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select() //接口所在的包 .apis(RequestHandlerSelectors.basePackage("com.example.swaggerdemo.controller")) .paths(PathSelectors.any()).build(); }}至此,咱们就能够拜访http://localhost:8080/swagger-ui.html看到swagger为咱们提供的在线调试和在线接口文档的页面了 ...

October 10, 2020 · 1 min · jiezi

关于springboot:09springboot工程中的热部署实现

热部署简介Spring Boot 开发者为Spring Boot我的项目中提供了一个热部署(spring-boot-devtools)模块,反对我的项目的热部署(批改了某些资源当前无需重启服务),以进步开发效率.其底层其实是借助了两个类加载器做了具体实现,一个类加载器加载不变class,一个类加载器加载可能变动类,以提供类的热部署性能. 热部署环境初始化本次热部署的演示在IDEA开发中进行实现,其它工具能够本人通过搜索引擎进行学习。 IDEA 启动主动编译,如图所示: IDEA工具中启动注册窗口(按ctrl+shift+alt+/),如图所示: 抉择编译构建配置,如图所示: 热部署在我的项目中利用在须要热部署的我的项目或module中增加如下依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope></dependency>依赖下载当前,可重启reload我的项目,而后当咱们批改了src/main/java目录下的java文件或批改了src/main/resources目录下的配置文件时,默认都会重启你的web服务器,然而批改了测试类或html文件不会主动重启和部署。 总结(summary)本大节对springboot工程中的热部署进行了剖析和实现,能够idea工具中实际整个过程。

October 10, 2020 · 1 min · jiezi

关于springboot:08springboot-工程下lombok的应用

背景剖析在理论的java我的项目中咱们创立的所有pojo类简直都要为属性增加set/get/toString等相干办法,所有的日志记录相干类可能都要创立日志等对象,这些样板代码既没有技术含量,又影响着代码的好看,同时反复的编码过程会在无形中加大咱们的工作量。 此时Lombok应运而生。 lombok简介概述Lombok是一个第三的Java库,它会主动插入编辑器和构建工具中,Lombok提供了一组有用的正文,用来通知编译过程中的编译工具,在源代码编译成字节码的过程中,在字节码中增加一些量样板代码。 罕用注解剖析@Setter 用于为形容的类生成setter办法,不蕴含final润饰属性。@Getter 用于为形容的类生成getter办法。@ToString 用于为形容的类增加toString办法。@EqualsAndHashCode 用于为形容的类,生成hashCode和equals办法。@NoArgsConstructor 用于为形容的类生成无参的构造方法。@AllArgsConstructor 用于为形容的类生成蕴含类中所有字段的构造方法。@Data用于为形容的类生成setter/getter、equals、canEqual、hashCode、toString办法,如为final属性,则不会为该属性生成setter办法。@Slf4J 用于为形容的类增加一个日志属性对象。lombok装置idea中的装置配置第一步:关上idea的设置窗口,找到plugins菜单,搜寻lombok进行装置,如图所示: 第二步:启动注解解决,如图所示: 第三步:重启idea(可选,有的idea版本须要)。 sts中的装置配置本人百度尝试。 lombok在maven我的项目中利用第一步:增加lombok依赖。 <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>annotationProcessor</scope></dependency>第二步:在类上利用lombok注解。 @Data @NoArgsConstructor @AllArgsConstructor public class Goods { private Long id; private String name; private String remark; private Date createdTime;}第三步:编写单元测试类检测Lombok注解利用 @Slf4j@SpringBootTestpublic class GoodsTests{ @Test void testGoods(){ Goods g=new Goods(); g.setId(100L); g.setName("Lombok"); log.info("id的值为{}",g.getId()); log.info("name的值为{}",g.getName()); }}总结(Summary)本大节次要对lombok做了一个剖析,装置和配置,并结合实际我的项目解说了lombok的利用场景及具体利用过程。

October 10, 2020 · 1 min · jiezi

关于springboot:springboot中properties配置文件读取中文乱码mac

mac与windows的差异只在于菜单地位有点不同, 解决形式是统一的对于这里提到的中文乱码问题, 是在properties文件中增加中文, 而后应用单元测试将后果打印在控制台, 后果呈现乱码 网上很多"解答"提到的要么是properties文件中增加参数, 要么是pom.xml文件中增加依赖, 要么是在FileEncoding中将编码设置成UTF-8 以上办法我都试过, 都没无效 其实这里的根本原因是: properties文件是应用ASCII编码, 而中文是UTF-8, 所以呈现了乱码 解决形式是在FileEncoding菜单中勾选Transparent native-to-ascii conversion

October 9, 2020 · 1 min · jiezi