一步一步构建springboot
1 初始化springboot
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build>
2 添加swagger
参考文章: springboot 2.7.0 配置swagger 3_Lab_l的博客-优快云博客
springboot 2.7.0 配置swagger 3
2.1:pom.xml 添加依赖 使用新版UI
<dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <!--在引用时请在maven中央仓库搜索3.X最新版本号--> <version>3.0.3</version> </dependency>
2.2:在启动类Application中加上注解
package com.example.swagger; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import springfox.documentation.oas.annotations.EnableOpenApi; @SpringBootApplication(exclude={DataSourceAutoConfiguration.class}) //exclude={DataSourceAutoConfiguration.class}:在没有连接数据库的情况下进行测试 @EnableOpenApi public class SwaggerApplication { public static void main(String[] args) { SpringApplication.run(SwaggerApplication.class, args); } }
第2.3:配置接口文档config
package com.example.swagger.config; import io.swagger.annotations.ApiOperation; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.oas.annotations.EnableOpenApi; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; @Configuration @EnableOpenApi public class SwaggerConfig { @Bean public Docket createRestApi(){ return new Docket(DocumentationType.OAS_30) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("Swagger3接口文档") .description("前后端分离的接口文档") .version("1.0") .build(); }
}
2.4 在application.properties文件中加入语句
spring.mvc.pathmatch.matching-strategy: ANT_PATH_MATCHER
2.7.0同样不支持swagger3的折衷配置,考虑升级Springboot版本或降级版本
除了参考中的springboot 2.6会有这样的问题,2.7也存在这样的问题,
如果不加的话会报错
Cause by:Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException错误原因:Springfox使用的路径匹配是基于AntPathMatcher的,而Spring Boot 2.6.X使用的是PathPatternMatcher
2.5 打开地址
http://localhost:8081/swagger-ui/index.html
3 支持mysql
Spring Boot 入门(六)使用MySQL - 小小渔 - 博客园
3.1 添加pom依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
3.2 添加配置
# 数据库设置 spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
3.3 代码
package com.example.demo.controller; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class HelloWorldController { @Autowired JdbcTemplate jdbcTemplate; @RequestMapping("/hello") public String index() { return "Hello World"; } @RequestMapping("/setMySQLKey") public String setMySQLKey(String val) { String sql = "INSERT INTO test_table(`name`) VALUES(?)"; jdbcTemplate.update(sql, new Object[]{val}); return "true"; } @RequestMapping("/getMySQLKey") public List<String> getMySQLKey() { String sql = "SELECT name FROM test_table"; List<String> nameList = jdbcTemplate.queryForList(sql, String.class); return nameList; } }
4 支持mybatis
-
mybatis支持自定义sql和注解上写sql
4.1 pom 配置
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.2</version> </dependency>
4.2 配置文件配置
xml 文件放到resouces文件下的mapper文件下
mybatis.mapper-locations: classpath:mapper/*.xml
在Application启动文件配置扫描持久化层的路径的注解@MapperScan
@MapperScan(value = "com.wlt.plus.mapper")
4.3 添加代码
com.wlt.plus.mapper 中配置自定义的slq 和xml中的sql
package com.wlt.plus.mapper; import com.wlt.plus.entity.Student; import org.apache.ibatis.annotations.*; import org.springframework.stereotype.Repository; import java.util.List; @Mapper @Repository public interface StudentMapper { @Select("select * from student limit 2 ") List<Student> getAllStudent(); @Insert("insert into student(id,name)values(#{id},#{name})") int addStudent(Student student); @Update("update student set name=#{name} where id=#{id}") int updateStudent(Student student); @Delete("delete from student where id=#{id}") int delStudent(String id); List<Student> getAllStudent1(); int updateStudent1(Student student); int delStudent1(String id); }
student.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.wlt.plus.mapper.StudentMapper"> <select id="getAllStudent1" resultType="com.wlt.plus.entity.Student"> select * from student limit 10 </select> <update id="updateStudent1"> update student set name=#{name} where id=#{id} </update> <delete id="delStudent1"> delete from student where id=#{id} </delete> </mapper>
实体文件代码 注意这里使用了lombok的插件
package com.wlt.plus.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data //使用lombok减少get、set、有参无参构造函数、tostring等方法的冗余 @AllArgsConstructor @NoArgsConstructor public class Student { private Long id; /** * 姓名 */ private String name; /** * 年龄 */ private Integer age; /** * 邮箱 */ private String email; }
controller 使用配置
@RestController @RequestMapping("/test") public class StudentController { @Autowired private StudentMapper studentMapper; @ApiOperation("查询") @GetMapping("/getStudentAll") public List<Student> getStudentAll(){ return studentMapper.getAllStudent1(); } @ApiOperation("增加") @GetMapping("/addStudent") public List<Student> addStudent(){ Student stu=new Student(); stu.setName("测试"); studentMapper.addStudent(stu); return studentMapper.getAllStudent(); } @ApiOperation("改变") @GetMapping("/updateStudent") public List<Student> updateStudent(){ Student stu=new Student(); stu.setEmail("f2adf775-3cfa-4e25-97bc-ec5676e15594"); stu.setName("修改了用户"); studentMapper.updateStudent(stu); return studentMapper.getAllStudent(); } @ApiOperation("删除") @GetMapping("/delStudent") public List<Student> delStudent(){ String stuId="f2adf775-3cfa-4e25-97bc-ec5676e15594"; studentMapper.delStudent(stuId); return studentMapper.getAllStudent(); } }
5 支持数据源Druid
springboot 学习(五) springboot使用druid - 黄易安 - 博客园
5.1 pom 配置
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
5.2 配置文件中切换数据源,同时配置druid属性
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource ### 连接池配置 spring.datasource.initialSize=1 spring.datasource.minIdle=2 spring.datasource.maxActive=2 # 配置获取连接等待超时的时间 spring.datasource.maxWait=60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 spring.datasource.timeBetweenEvictionRunsMillis=60000 # 配置一个连接在池中最小生存的时间,单位是毫秒 spring.datasource.minEvictableIdleTimeMillis=300000 spring.datasource.validationQuery=SELECT 1 FROM DUAL spring.datasource.testWhileIdle=true spring.datasource.testOnBorrow=false spring.datasource.testOnReturn=false # 打开PSCache,并且指定每个连接上PSCache的大小 spring.datasource.poolPreparedStatements=true spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
5.3 添加代码
由于DruidDataSource需要使用上述的配置,在添加到容器中,就不能使用springboot自动生成,这时需要我们自己添加 DruidDataSource 组件到容器中,并绑定属性;代码如下
@Configuration public class DruidConfig { /* 将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建 绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效 @ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中 前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中 */ @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druidDataSource() { return new DruidDataSource(); } //配置 Druid 监控管理后台的Servlet; //内置 Servlet 容器时没有web.xml文件,所以使用 Spring Boot 的注册 Servlet 方式 @Bean public ServletRegistrationBean a(){ ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*"); Map<String, String> initParameters = new HashMap<>(); initParameters.put("loginUsername","admin"); initParameters.put("loginPassword","12346"); bean.setInitParameters(initParameters); return bean; } ## 配置过滤请求,需要统计哪些sql的信息 //配置 Druid 监控 之 web 监控的 filter //WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计 @Bean public FilterRegistrationBean webStatFilter() { FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); //exclusions:设置哪些请求进行过滤排除掉,从而不进行统计 Map<String, String> initParams = new HashMap<>(); initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*"); bean.setInitParameters(initParams); //"/*" 表示过滤所有请求 bean.setUrlPatterns(Arrays.asList("/*")); return bean; }
5.4 登录验证
配置完毕后,我们可以选择访问 :http://localhost:8081/druid/login.html
6 支持mybatisPlus
切换分支plus
6.1 pom 支持
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.5</version> </dependency>
6.2 代码
CREATE TABLE `money` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL DEFAULT '' COMMENT '用户名', `money` int(26) NOT NULL DEFAULT '0' COMMENT '有多少钱', `is_deleted` tinyint(1) NOT NULL DEFAULT '0', `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `update_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', PRIMARY KEY (`id`), KEY `name` (`name`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
添加MapperScan
@MapperScan(value = "com.wlt.plus.mapper")
添加domain 对应的表结构的bean
@Data public class Money { @TableId(type = IdType.AUTO) // 自增策略 private Integer id; private String name; private Long money; private Integer isDeleted; private Timestamp createAt; private Timestamp updateAt; }
添加Mapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.wlt.plus.entity.Money; public interface MoneyMapper extends BaseMapper<Money> {}
应用
Money po = new Money(); po.setName("mybatis plus user"); Random random = new Random(); po.setMoney(222L); po.setIsDeleted(0); // 添加一条数据 po.setIsDeleted(0); moneyMapper.insert(po); // 查询 List<Money> list = moneyMapper.selectList(new QueryWrapper<Money>().lambda().eq(Money::getName, po.getName())); System.out.println("after insert: " + list); // 修改 po.setMoney(po.getMoney() + 300); moneyMapper.updateById(po); System.out.println("after update: " + moneyMapper.selectById(po.getId())); // 删除 // moneyMapper.deleteById(po.getId()); // 查询 HashMap<String, Object> queryMap = new HashMap<>(2); queryMap.put("name", po.getName()); System.out.println("after delete: " + moneyMapper.selectByMap(queryMap));
6.3 自动生成