简化Spring应用开发的一个框架,整个Spring技术栈的一个大整合。
官方网站:https://spring.io/projects
优点:
- 快速创建Spring项目,使用嵌入式的服务,内置了Tomcat
- starters(启动器)自动依赖与版本控制
- 无需配置XML,开箱即用
系统要求:
Java 8、Maven 3.3+
maven配置:
给maven 的settings.xml配置文件的profiles标签添加
nexus-aliyun central Nexus aliyun http://maven.aliyun.com/nexus/content/groups/public jdk-1.8 true1.8 1.8 1.8 1.8
特点:
-
依赖管理
父项目做依赖管理、开发导入starter场景启动类、无需关注版本号
-
自动配置
自动配置了tomcat、配置SpringMVC、Web常见功能
常用注解:
@Configuration //告诉SpringBoot这是一个配置类 == 配置文件 @Bean //给容器中添加组件。 @ComponentScan //包扫描 @Import({User.class, User2.class}) // 给容器中自动创建出这两个类型的组件 @Conditional //条件装配 ,注入 @ImportResource //原生配置文件引入 @Component //实现Bean的注入 @ConfigurationProperties //配置绑定 取到properties文件中的内容,封装到Bean中 配合@Component注解 @EnableConfigurationProperties 同上,就不需要加 @Component
Spring自动配置:
启动类 SpringBootApplication 1.@SpringBootConfiguration - @Configuration //配置类 2.@EnableAutoConfiguration @AutoConfigurationPackage 指定了默认的包规则,将指定的一个包下的所有组件导入进来 @Import() 给容器中批量导入一些组件 按需开启自动配置项 xxxxAutoConfiguration ,按照条件装配规则 3.@ComponentScan() //包扫描 总结: SpringBoot先加载所有的自动配置类,每个自动动,按配置类条件去生效,生效后就给容器配置很多的组件,容器有这些组件,就有了这些功能。 如果我们定制配置,可以直接@Bean替换底层默认的组件。核心功能 yaml配置文件
# yaml表示以上对象 person: userName: zhangsan birth: 2019/12/12 20:12:33 # 数组 List简化开发arr arr: - jpg - png # map Map > allPets; allPets: sick: - {name: tom} - {name: jerry,weight: 47} health: [{name: mario,weight: 47}] @ConfigurationProperties(prefix = "mongodb") @Component public class Person { private String userName; }
-
lombok
org.projectlombok lombok1.18.10 -
dev-tools
org.springframework.boot spring-boot-devtoolstrue
静态目录:/static /public /resources /META-INF/resources
改变默认的静态资源路径
spring:
# 设置静态资源访问前缀,默认无前缀,访问:localhost:8080/res/xxx.css
mvc:
static-path-pattern: /res
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestURI = request.getRequestURI();
log.info("preHandle拦截的请求路径是{}",requestURI);
//登录检查逻辑
HttpSession session = request.getSession();
Object loginUser = session.getAttribute("LoginState");
if(loginUser != null){
//放行
return true;
}
//拦截住。未登录。跳转到登录页
request.setAttribute("msg","请先登录");
request.getRequestDispatcher("/login").forward(request,response);
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("postHandle执行{}",modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("afterCompletion执行异常{}",ex);
}
}
2.配置拦截器
package com.good.yan.config.interceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class AdminWebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home/list");
registry.addViewController("/index.html").setViewName("home/list");
registry.addViewController("/index").setViewName("home/list");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("
@PostMapping("/upload")
public String upload(@RequestPart("headerImg") MultipartFile headerImg,
@RequestPart("photos") MultipartFile[] photos) throws IOException {
if(!headerImg.isEmpty()){
//保存到文件服务器,OSS服务器
headerImg.transferTo(new File("H:\cache\"+headerImg.getOriginalFilename()));
}
if(photos.length > 0){
for (MultipartFile photo : photos) {
if(!photo.isEmpty()){
photo.transferTo(new File("H:\cache\"+photo.getOriginalFilename()));
}
}
}
return "上传ok";
}
异常处理
自定义错误页:在templates目录下寻找error目录下的404.html 、5xx.html的页面。
定义全局异常:
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
// @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR,reason = "用户访问太多")
@ExceptionHandler(value = Exception.class)
public Map defaultErrorHandler(Exception e) {
log.error("Exception", e);
Map map = new HashMap();
map.put("code", FIVE);
map.put("message", e.getMessage());
return map;
}
}
数据访问
SpringBoot连接Mysql
# 1.引入包# 2.修改yml配置文件 spring: datasource: username: 用户名 password: 密码 # mysql8版本以上的驱动包,需要指定以下时区 url: jdbc:mysql://127.0.0.1:3306/数据库?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8 driver-class-name: com.mysql.cj.jdbc.Driver mysql mysql-connector-java
使用Druid数据源
官网地址:https://github.com/alibaba/druid
# 1.引入包# 2.修改yml配置文件 spring: datasource: url: jdbc:mysql://localhost:3306/db username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver druid: initial-size: 5 min-idle: 5 max-active: 20 max-wait: 60000 #... # 监控哪些包 aop-patterns: com.good.yan.modules.* # 底层开启功能,stat(sql监控),wall(防火墙) filters: stat,wall stat-view-servlet: # 配置监控页功能 enabled: true # 开启维护功能 login-username: admin # 访问的用户名和密码 login-password: admin resetEnable: false # 是否重置按钮启用 web-stat-filter: # 监控web enabled: true urlPattern: *.xml com.alibaba druid-spring-boot-starter 1.1.17
创建generator.xml配置文件
运行,点击maven中的generate进行运行。
# 1.引包# 2.配置分页插件 com.github.pagehelper pagehelper 5.2.0 # 3.案例 public void testPageHelper() throws IOException { PageHelper.startPage(1, 2); List all = billMapper.findAll(); // 参数:数据 、 页码 尽量是奇数 1,2,3,4,5 PageInfo pageInfo = new PageInfo<>(all,5); }
常用数据:
- pageNum:当前页的页码
- pageSize:每页显示的条数
- size:当前页显示的真实条数
- total:总记录数
- pages:总页数
- prePage:上一页的页码
- nextPage:下一页的页码
- isFirstPage/isLastPage:是否为第一页/最后一页
- hasPreviousPage/hasNextPage:是否存在上一页/下一页
- navigatePages:导航分页的页码数
- navigatepageNums:导航分页的页码,[1,2,3,4,5]



