一、引言
1.什么是Springboot?
定义:快速开发的微框架(配置少)作用:简化Spring应用的初始创建和开发过程原则:遵从约定大于配置,用特定的方式进行配置,不需要原先样板式配置(spring.xml , springmvc.xml , web.xml , 依赖…)总结:Springboot简化了spring应用的开发springboot(工厂+控制)=spring+springmvc2. springboot的特点
创建独立的Spring应用程序(一个容器配置文件,并有独立的持久层Springboot jpa,我们使用Mybatis)嵌入的Tomcat,无需部署WAR文件简化Maven配置(依赖导入)自动配置Spring框架,无需xml配置
二、 如何创建springboot项目
环境要求:
- MAVEN 3.x+
- Spring FrameWork 5.x+
- JDK8.x +
- Spring Boot 2.2.x+
1.引入依赖
<!--继承springboot的父项目--><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.5.RELEASE</version></parent><dependencies><!--引入springboot的web支持--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies>2.引入配置文件(
项目中src/main/resources/application.yml或porperties)
可在其中配置如:端口号server.port,应用路径(默认访问不需要)server.servlet.context-path等等
3 建包(src下必须有子包)并创建控制器
//在项目中创建指定的包结构(com.controller)@RestControllerpublicclassHelloController{@RequestMapping("/hello")publicStringhello(){System.out.println("======hello world=======");return"hello";}}.4 编写入口类在子包外
原因: @SpringBootApplication标识这是入口类,子注解中会自动包扫描,扫描当前目录下所有子包的注解
//在项目中com包下创建入口类 Application@SpringBootApplicationpublicclassApplication{publicstaticvoidmain(String[]args){SpringApplication.run(Application.class,args);}}# 运行main启动项目 # 访问项目:http://localhost:8080/hello(注意:springboot的项目默认没有项目名)
其他创建方式:
1.spring官网下载解压,idea通过maven导入
2.IDEA新建时使用Spring initalizr
三、Springboot自动配置分析
结论:
所有的自动配置都放在spring.factories
文件的任意一个键都是一个配置例:
@Configuration——标志该类为配置类
@Conditional…——当不满足条件,则该配置生效
@EnableConfigurationProperties…——将配置文件的值与properties中的值绑定,并注入到IOC中
public class xxxAutoConfiguration{…}
补充:
1.启动类中run方法有返回值,类型为Application类型,其实就是spring容器,可以使用引用.getBean()方法获取对象
2.入口类实现CommandLineRunner或ApplicationRunner接口,接口实现run方法,在Springboot容器创建好立即执行,可以自定义操作,如:数据库连接,读取文件等
四、配置文件的其他用法
1.引用配置文件中的key、value给类中属性赋值
@ConfigurationProperties(prefix="") 作用:将配置文件中前缀为......的key给属性赋值(key值和属性名一样就行) @PropertySource(value="classpath:......properties")——@value 作用:加载指定配置文件properties,并使用@value给属性赋值 # @ConfigurationProperties和@value的区别 批量注入 单个指定 支持松散绑定 不支持松散绑定 松散绑定(yml中使用-分割或驼峰命名法也能对应上) 不支持spEL 支持spEL 支持JSR303数据校验 不支持JSR303数据校验 支持复杂类型封装 不支持复杂类型封装2. springboot中配置文件的拆分
#说明: 在实际开发过程中生产环境和测试环境有可能是不一样的生产环境:application-prod.yml/properties 开发环境:application-dev.yml/properties 测试环境:application-test.yml/properties 使用Spring.profiles.active=prod等进行切换 注: 当yml和properties同时配置,默认使用properties3.配置文件加载位置
优先级:
项目路径下config文件夹下配置文件>项目路径下当前路径下配置文件>资源路径下config文件夹配置文件>资源路径下配置文件
五、web开发
1.静态资源源码探究
查看webMVCAutoConfiguration.class,
1.注解@EnableConfigurationProperties读取WebMVCProperties.class,该类中设置静态资源属性:staticPathPattern=“/**”
2.由于该类上有注解@ConfigurationProperties(prefix=“spring.mvc”),在yml或properties文件中设置spring.mvc.staticPathPattern=““会让原来默认的失效
3.当没有改变默认属性,查看addResourceHandlers()方法,读取的是webjars或默认路径
默认路径:addResourceHandlers()方法中的getStaticLocations()方法得到:classpath:”/META-INF/resources”,“/resources”,“/static/”,“/public/”
2.Springboot集成jsp页面
Springboot默认设计不支持jsp,支持的是thymeleaf(类似于vue)
# 1.导入jsp的解析依赖(org.apache.tomcat.embed——tomcat-embed-jasper) # 2.设置视图解析器: spring.mvc.view.prefix:/ suffix:jsp # 3.设置当前运行环境: 当前项目的configuration,设置environment下的working directory:$MODULE_DIR$ # 4.在main下设置webapp目录,并设置项目结构web,开发的jsp放到这个目录下 # 5.静态资源的热部署:server.servlet.jsp.init-paramters:development:true六、springboot中管理对象创建
1. 简单对象
在springboot中可以管理自定义的
简单组件对象的创建可以直接使用注解形式创建,如:使用 @Repository @Service @Controller 以及@Component
2 简单对象+复杂对象
在springboot中如果要管理
复杂对象必须使用@Configuration + @Bean注解进行管理
@Configuration(推荐)|@Component(不推荐)publicclassBeans{@Bean@Scope("单例还是多例")publicUsergetUser(){returnnewUser();}}七、扩展SpringMVC+自定义组件(视图跳转、拦截器)
说明:springboot在保留springmvc默认配置情况下,允许我们扩展,需手写一个javaConfig配置类实现webMvcConfigure接口
@configurationpublicclassMyConfigimplementsWebMvcConfigurer{//1.自定义视图控制publicvoidaddViewControllers(ViewControllerRegistryregistry){//只要是/请求,都执行index逻辑registry.addViewController("/").setViewName("index")}//springboot拦截器(自定义拦截器需实现HandlerInterceptor接口,并注册到spring容器:@Component)publicvoidaddInterceptors(InterceptorRegistryregistry){registry.addInterceptor(newMyInterceptor()).addPathPatterns("拦截路径").excludePathPatterns("忽略路径")}}
八、字符集过滤器
第一种:修改properties文件
server.servlet.encoding.enabled=true server.servlet.encoding.charset=utf-8 server.servlet.encoding.force=true第二种:自定义过滤器
@ConfigurationpublicclassWebApplicationConfig{@BeanpublicFilterRegistrationBeanfilterRegistrationBean(){FilterRegistrationBeanbean=newFilterRegistrationBean();CharacterEncodingFiltercef=newCharacterEncodingFilter();cef.setEncoding("utf-8");cef.setForceEncoding(true);bean.setFilter(cef);bean.addUrlPatterns("/");returnbean;}}# 关闭系统默认配置 server.servlet.encoding.enabled=false
九、springboot集成mybatis
1.引入依赖(mybatis-spring-boot-starter,druid,mysql)
2.建表,实体类(entity)
3.mapper文件,dao接口
4.service接口和实现类
5.配置文件spring:datasource:type:org.apache.commons.dbcp.BasicDataSource#指定连接池类型driver-class-name:com.mysql.jdbc.Driver#指定驱动url:jdbc:mysql://localhost:3306/cmfz#指定urlusername:root#指定用户名password:root#指定密码#配置文件中加入如下配置:mybatis:mapper-locations:classpath:com/mapper/*.xml#指定mapper配置文件位置type-aliases-package:com.baizhi.entity#指定起别名来的类6.入口类中加入如下配置
@SpringBootApplication@MapperScan("com.baizhi.dao")//必须在入口类中加入这个配置publicclassApplication{publicstaticvoidmain(String[]args){SpringApplication.run(Application.class,args);}}7.开发controller
druid还有日志监控功能哦!
十、springboot事务控制实现
在application启动类上加@EnableTransactionManagement注解
service方法上添加@transactional注解即可
十一、logback日志的集成
Logback是由log4j创始人设计的又一个开源日志组件。目前,logback分为三个模块:logback-core,logback-classic和logback-access。是对log4j日志展示进一步改进
1.日志级别
日志级别:DEBUG < INFO < WARN < ERROR
日志级别由低到高: 日志级别越高输出的日志信息越少
2.项目中日志分类
日志分为两类
一种是rootLogger : 用来监听项目中所有的运行日志 包括引入依赖jar中的日志
一种是logger : 用来监听项目中指定包中的日志信息
3. 项目中使用
第一种:使用默认日志配置
#修改日志级别 logging.level.root=debug #修改子日志级别 logging.level.com.service=info #日志输出保存文件位置 logging.file.name=D://log.txt第二种:自定义logback.xml(不推荐),必须放在项目根目录中 且名字必须为logback.xml
<?xml version="1.0" encoding="UTF-8" ?><configuration><!--定义项目中日志输出位置--><appendername="stdout"class="ch.qos.logback.core.ConsoleAppender"><!--定义项目的日志输出格式--><!--定义项目的日志输出格式--><layoutclass="ch.qos.logback.classic.PatternLayout"><pattern>[%p] %d{yyyy-MM-dd HH:mm:ss} %m %n</pattern></layout></appender><!--项目中跟日志控制--><rootlevel="INFO"><appender-refref="stdout"/></root><!--项目中指定包日志控制--><loggername="com.baizhi.dao"level="DEBUG"/></configuration>
4. 具体类中使用日志
@Controller@RequestMapping("user")publicclassUserController{privateLoggerlogger=org.slf4j.LoggerFactory.getLogger(this.getClass());@RequestMapping("findAll")publicStringfindAll(Stringname){logger.debug("debug接收的姓名是: "+name);return"index";}}十二、面向切面编程
springboot是对原有项目中spring框架和springmvc的进一步封装,因此在springboot中同样支持spring框架中AOP切面编程,不过在springboot中为了快速开发仅仅提供了注解方式的切面编程.
1.使用
1.引入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>2.相关注解
/** @Aspect 用来类上,代表这个类是切面 @Before 用在方法上 表示前置通知方法 参数:JoinPoint @After 用在方法上 表示后置通知方法 参数:JoinPoint @Around用在方法上 表示环绕通知方法 参数:ProceedingJoinPoint @Afterthrowing用在方法上表示异常通知方法 参数:JoinPoint Exception **/
2.示例
//环绕切面@Aspect@ComponentpublicclassMyAspect{@Around("execution(* com.baizhi.service.*.*(..))")publicObjectbefore(ProceedingJoinPointproceedingJoinPoint)throwsThrowable{System.out.println("进入环绕通知");proceedingJoinPoint.getTarget();//目标对象proceedingJoinPoint.getSignature();//方法签名proceedingJoinPoint.getArgs();//方法参数Objectproceed=proceedingJoinPoint.proceed();//放行执行目标方法System.out.println("目标方法执行之后回到环绕通知");returnproceed;//返回目标方法返回值}}
注意: 环绕通知存在返回值,参数为ProceedingJoinPoint,如果执行放行,不会执行目标方法,一旦放行必须将目标方法的返回值返回,否则调用者无法接受返回数据
十三、文件上传下载
1.文件上传
1.表单页面
<formaction="路径...."method="post"enctype="multipart/form-data"><inputtype="file"name="photo"><inputtype="submit"value="上传"></form>2.编写控制器
@Controller@RequestMapping("/file")publicclassFileController{@RequestMapping("/upload")publicStringupload(MultipartFilephoto,HttpServletRequestrequest)throwsIOException{StringrealPath=request.getRealPath("/upload");aa.transferTo(newFile(realPath,photo.getOriginalFilename()));//文件上传return"index";}}
- 修改文件上传大小
#上传时出现如下异常: 上传文件的大小超出默认配置 默认10Mnested exception is java.lang.IllegalStateException:>org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededExc>eption:the request was rejected because its size (38443713) exceeds the>configured maximum (10485760)#修改上传文件大小:spring:http:multipart:max-request-size:209715200#用来控制文件上传大小的限制max-file-size:209715200#用来指定服务端最大文件大小
2.文件下载
1.页面提供下载文件链接
<ahref="../file/download?fileName=corejava.txt">corejava.txt</a>2.开发控制器
@RequestMapping("/download")publicvoiddownload(StringfileName,HttpServletRequestrequest,HttpServletResponseresponse)throwsException{StringrealPath=request.getRealPath("/upload");FileInputStreamis=newFileInputStream(newFile(realPath,fileName));ServletOutputStreamos=response.getOutputStream();response.setHeader("content-disposition","attachment;fileName="+URLEncoder.encode(fileName,"UTF-8"));IOUtils.copy(is,os);IOUtils.closeQuietly(is);IOUtils.closeQuietly(os);}
十四、 war包部署
作用:tomcat的webapp下放入war包,运行tomcat即可访问注意:war包部署后项目配置的端口和项目名会失效,使用tomcat默认的
步骤
1.pom.xml设置打包方式为war
<packaging>war</packaging>2.在插件中指定入口类
<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><!--使用热部署出现中文乱码解决方案--><configuration><fork>true</fork><!--增加jvm参数--><jvmArguments>-Dfile.encoding=UTF-8</jvmArguments><!--指定入口类--><mainClass>com.baizhi.Application</mainClass></configuration></plugin></plugins></build>3.排除内嵌的tomcat
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId><scope>provided</scope><!--去掉内嵌tomcat--></dependency><dependency><groupId>org.apache.tomcat.embed</groupId><artifactId>tomcat-embed-jasper</artifactId><scope>provided</scope><!--去掉使用内嵌tomcat解析jsp--></dependency>4.配置入口类
//1.继承SpringBootServletInitializer//2.覆盖configure方法publicclassApplicationextendsSpringBootServletInitializer{publicstaticvoidmain(String[]args){SpringApplication.run(Application.class,args);}@OverrideprotectedSpringApplicationBuilderconfigure(SpringApplicationBuilderbuilder){>returnbuilder.sources(Application.class);}}
十五、springboot中devtools热部署
为了进一步提高开发效率,springboot为我们提供了全局项目热部署,日后在开发过程中修改了部分代码以及相关配置文件后,不需要每次重启使修改生效,在项目中开启了springboot全局热部署之后只需要在修改之后等待几秒即可使修改生效。
开启热部署
1.项目中引入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional></dependency>2.设置idea中支持自动编译
# 1.开启自动编译 Preferences(Settings) | Build, Execution, Deployment | Compiler -> 勾选上 Build project automatically 这个选项 # 2.开启允许在运行过程中修改文件 ctrl + alt + shift + / ---->选择1.Registry ---> 勾选 compiler.automake.allow.when.app.running 这个选项3.启动项目检测热部署是否生效(启动出现如下日志代表生效)
2019-07-17 21:23:17.566 INFO 4496 --- [ restartedMain] com.baizhi.InitApplication : Starting InitApplication on chenyannandeMacBook-Pro.local with PID 4496 (/Users/chenyannan/IdeaProjects/ideacode/springboot_day1/target/classes started by chenyannan in /Users/chenyannan/IdeaProjects/ideacode/springboot_day1) 2019-07-17 21:23:17.567 INFO 4496 --- [ restartedMain] com.baizhi.InitApplication : The following profiles are active: dev 2019-07-17 21:23:17.612 INFO 4496 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@66d799c5: startup date [Wed Jul 17 21:23:17 CST 2019]; root of context hierarchy 2019-07-17 21:23:18.782 INFO 4496 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8989 (http) 2019-07-17 21:23:18.796 INFO 4496 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2019-07-17 21:23:18.797 INFO 4496 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.20