SpringBoot微框架 一、引言1.什么是Springboot定义快速开发的微框架配置少作用简化Spring应用的初始创建和开发过程原则遵从约定大于配置用特定的方式进行配置不需要原先样板式配置(spring.xml , springmvc.xml , web.xml , 依赖…)总结Springboot简化了spring应用的开发springboot工厂控制springspringmvc2. springboot的特点创建独立的Spring应用程序一个容器配置文件并有独立的持久层Springboot jpa我们使用Mybatis嵌入的Tomcat无需部署WAR文件简化Maven配置依赖导入自动配置Spring框架无需xml配置二、 如何创建springboot项目环境要求:MAVEN 3.xSpring FrameWork 5.xJDK8.x Spring Boot 2.2.x1.引入依赖!--继承springboot的父项目--parentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion2.2.5.RELEASE/version/parentdependencies!--引入springboot的web支持--dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependency/dependencies2.引入配置文件(项目中src/main/resources/application.yml或porperties)可在其中配置如端口号server.port应用路径(默认访问不需要)server.servlet.context-path等等3 建包(src下必须有子包)并创建控制器//在项目中创建指定的包结构com.controllerRestControllerpublicclassHelloController{RequestMapping(/hello)publicStringhello(){System.out.println(hello world);returnhello;}}.4 编写入口类在子包外原因 SpringBootApplication标识这是入口类子注解中会自动包扫描扫描当前目录下所有子包的注解//在项目中com包下创建入口类 ApplicationSpringBootApplicationpublicclassApplication{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(valueclasspath:......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.activeprod等进行切换 注 当yml和properties同时配置默认使用properties3.配置文件加载位置优先级项目路径下config文件夹下配置文件项目路径下当前路径下配置文件资源路径下config文件夹配置文件资源路径下配置文件五、web开发1.静态资源源码探究查看webMVCAutoConfiguration.class1.注解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 以及Component2 简单对象复杂对象在springboot中如果要管理复杂对象必须使用Configuration Bean注解进行管理Configuration(推荐)|Component(不推荐)publicclassBeans{BeanScope(单例还是多例)publicUsergetUser(){returnnewUser();}}七、扩展SpringMVC自定义组件视图跳转、拦截器说明springboot在保留springmvc默认配置情况下允许我们扩展需手写一个javaConfig配置类实现webMvcConfigure接口configurationpublicclassMyConfigimplementsWebMvcConfigurer{//1.自定义视图控制publicvoidaddViewControllers(ViewControllerRegistryregistry){//只要是/请求都执行index逻辑registry.addViewController(/).setViewName(index)}//springboot拦截器自定义拦截器需实现HandlerInterceptor接口并注册到spring容器ComponentpublicvoidaddInterceptors(InterceptorRegistryregistry){registry.addInterceptor(newMyInterceptor()).addPathPatterns(拦截路径).excludePathPatterns(忽略路径)}}八、字符集过滤器第一种修改properties文件server.servlet.encoding.enabledtrue server.servlet.encoding.charsetutf-8 server.servlet.encoding.forcetrue第二种自定义过滤器ConfigurationpublicclassWebApplicationConfig{BeanpublicFilterRegistrationBeanfilterRegistrationBean(){FilterRegistrationBeanbeannewFilterRegistrationBean();CharacterEncodingFiltercefnewCharacterEncodingFilter();cef.setEncoding(utf-8);cef.setForceEncoding(true);bean.setFilter(cef);bean.addUrlPatterns(/);returnbean;}}# 关闭系统默认配置 server.servlet.encoding.enabledfalse九、springboot集成mybatis1.引入依赖mybatis-spring-boot-starterdruidmysql2.建表实体类(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.入口类中加入如下配置SpringBootApplicationMapperScan(com.baizhi.dao)//必须在入口类中加入这个配置publicclassApplication{publicstaticvoidmain(String[]args){SpringApplication.run(Application.class,args);}}7.开发controllerdruid还有日志监控功能哦十、springboot事务控制实现在application启动类上加EnableTransactionManagement注解service方法上添加transactional注解即可十一、logback日志的集成Logback是由log4j创始人设计的又一个开源日志组件。目前logback分为三个模块logback-corelogback-classic和logback-access。是对log4j日志展示进一步改进1.日志级别日志级别DEBUG INFO WARN ERROR日志级别由低到高: 日志级别越高输出的日志信息越少2.项目中日志分类日志分为两类一种是rootLogger : 用来监听项目中所有的运行日志 包括引入依赖jar中的日志一种是logger : 用来监听项目中指定包中的日志信息3. 项目中使用第一种使用默认日志配置#修改日志级别 logging.level.rootdebug #修改子日志级别 logging.level.com.serviceinfo #日志输出保存文件位置 logging.file.nameD://log.txt第二种自定义logback.xml(不推荐),必须放在项目根目录中 且名字必须为logback.xml?xml version1.0 encodingUTF-8 ?configuration!--定义项目中日志输出位置--appendernamestdoutclassch.qos.logback.core.ConsoleAppender!--定义项目的日志输出格式--!--定义项目的日志输出格式--layoutclassch.qos.logback.classic.PatternLayoutpattern[%p] %d{yyyy-MM-dd HH:mm:ss} %m %n/pattern/layout/appender!--项目中跟日志控制--rootlevelINFOappender-refrefstdout//root!--项目中指定包日志控制--loggernamecom.baizhi.daolevelDEBUG//configuration4. 具体类中使用日志ControllerRequestMapping(user)publicclassUserController{privateLoggerloggerorg.slf4j.LoggerFactory.getLogger(this.getClass());RequestMapping(findAll)publicStringfindAll(Stringname){logger.debug(debug接收的姓名是: name);returnindex;}}十二、面向切面编程springboot是对原有项目中spring框架和springmvc的进一步封装,因此在springboot中同样支持spring框架中AOP切面编程,不过在springboot中为了快速开发仅仅提供了注解方式的切面编程.1.使用1.引入依赖dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-aop/artifactId/dependency2.相关注解/** Aspect 用来类上,代表这个类是切面 Before 用在方法上 表示前置通知方法 参数JoinPoint After 用在方法上 表示后置通知方法 参数JoinPoint Around用在方法上 表示环绕通知方法 参数ProceedingJoinPoint Afterthrowing用在方法上表示异常通知方法 参数JoinPoint Exception **/2.示例//环绕切面AspectComponentpublicclassMyAspect{Around(execution(* com.baizhi.service.*.*(..)))publicObjectbefore(ProceedingJoinPointproceedingJoinPoint)throwsThrowable{System.out.println(进入环绕通知);proceedingJoinPoint.getTarget();//目标对象proceedingJoinPoint.getSignature();//方法签名proceedingJoinPoint.getArgs();//方法参数ObjectproceedproceedingJoinPoint.proceed();//放行执行目标方法System.out.println(目标方法执行之后回到环绕通知);returnproceed;//返回目标方法返回值}}注意: 环绕通知存在返回值,参数为ProceedingJoinPoint,如果执行放行,不会执行目标方法,一旦放行必须将目标方法的返回值返回,否则调用者无法接受返回数据十三、文件上传下载1.文件上传1.表单页面formaction路径....methodpostenctypemultipart/form-datainputtypefilenamephotoinputtypesubmitvalue上传/form2.编写控制器ControllerRequestMapping(/file)publicclassFileController{RequestMapping(/upload)publicStringupload(MultipartFilephoto,HttpServletRequestrequest)throwsIOException{StringrealPathrequest.getRealPath(/upload);aa.transferTo(newFile(realPath,photo.getOriginalFilename()));//文件上传returnindex;}}修改文件上传大小#上传时出现如下异常: 上传文件的大小超出默认配置 默认10Mnested exception is java.lang.IllegalStateException:org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException:the request was rejected because its size (38443713) exceeds theconfigured maximum (10485760)#修改上传文件大小:spring:http:multipart:max-request-size:209715200#用来控制文件上传大小的限制max-file-size:209715200#用来指定服务端最大文件大小2.文件下载1.页面提供下载文件链接ahref../file/download?fileNamecorejava.txtcorejava.txt/a2.开发控制器RequestMapping(/download)publicvoiddownload(StringfileName,HttpServletRequestrequest,HttpServletResponseresponse)throwsException{StringrealPathrequest.getRealPath(/upload);FileInputStreamisnewFileInputStream(newFile(realPath,fileName));ServletOutputStreamosresponse.getOutputStream();response.setHeader(content-disposition,attachment;fileNameURLEncoder.encode(fileName,UTF-8));IOUtils.copy(is,os);IOUtils.closeQuietly(is);IOUtils.closeQuietly(os);}十四、 war包部署作用:tomcat的webapp下放入war包,运行tomcat即可访问注意war包部署后项目配置的端口和项目名会失效使用tomcat默认的步骤1.pom.xml设置打包方式为warpackagingwar/packaging2.在插件中指定入口类buildpluginsplugingroupIdorg.springframework.boot/groupIdartifactIdspring-boot-maven-plugin/artifactId!--使用热部署出现中文乱码解决方案--configurationforktrue/fork!--增加jvm参数--jvmArguments-Dfile.encodingUTF-8/jvmArguments!--指定入口类--mainClasscom.baizhi.Application/mainClass/configuration/plugin/plugins/build3.排除内嵌的tomcatdependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-tomcat/artifactIdscopeprovided/scope!--去掉内嵌tomcat--/dependencydependencygroupIdorg.apache.tomcat.embed/groupIdartifactIdtomcat-embed-jasper/artifactIdscopeprovided/scope!--去掉使用内嵌tomcat解析jsp--/dependency4.配置入口类//1.继承SpringBootServletInitializer//2.覆盖configure方法publicclassApplicationextendsSpringBootServletInitializer{publicstaticvoidmain(String[]args){SpringApplication.run(Application.class,args);}OverrideprotectedSpringApplicationBuilderconfigure(SpringApplicationBuilderbuilder){returnbuilder.sources(Application.class);}}十五、springboot中devtools热部署​为了进一步提高开发效率,springboot为我们提供了全局项目热部署,日后在开发过程中修改了部分代码以及相关配置文件后,不需要每次重启使修改生效,在项目中开启了springboot全局热部署之后只需要在修改之后等待几秒即可使修改生效。开启热部署1.项目中引入依赖dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-devtools/artifactIdoptionaltrue/optional/dependency2.设置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.AnnotationConfigEmbeddedWebApplicationContext66d799c5: 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