SpringBoot学习资料_第1页
SpringBoot学习资料_第2页
SpringBoot学习资料_第3页
SpringBoot学习资料_第4页
SpringBoot学习资料_第5页
已阅读5页,还剩41页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

精品文档 1欢迎下载 SpringBoot 一 一 SpringSpring 介绍介绍 1 11 1 SpringBootSpringBoot 简介简介 在您第 1 次接触和学习 Spring 框架的时候 是否因为其繁杂的配置而退却了 在你第 n 次使用 Spring 框 架的时候 是否觉得一堆反复黏贴的配置有一些厌烦 那么您就不妨来试试使用 Spring Boot 来让你更易 上手 更简单快捷地构建 Spring 应用 Spring Boot 让我们的 Spring 应用变的更轻量化 比如 你可以仅仅依靠一个 Java 类来运行一个 Spring 引用 你也可以打包你的应用为 jar 并通过使用 java jar 来运行你的 Spring Web 应用 Spring Boot 的主要优点 为所有 Spring 开发者更快的入门 开箱即用 提供各种默认配置来简化项目配置 内嵌式容器简化 Web 项目 没有冗余代码生成和 XML 配置的要求 本章主要目标完成 Spring Boot 基础项目的构建 并且实现一个简单的 Http 请求处理 通过这个例子对 Spring Boot 有一个初步的了解 并体验其结构简单 开发快速的特性 1 21 2 系统要求 系统要求 Java 7 及以上 Spring Framework 4 1 5 及以上 本文采用本文采用 Java 1 8 0 73 Spring Boot 1 3 2 调试通过 调试通过 二 快速入门二 快速入门 精品文档 2欢迎下载 2 12 1 创建一个 创建一个 MavenMaven 工程工程 名为名为 springboot helloworldspringboot helloworld 类型为类型为 JarJar 工程项目工程项目 2 22 2 pompom 文件引入依赖文件引入依赖 org springframework bootorg springframework boot spring boot starter parentspring boot starter parent 1 3 3 RELEASE1 3 3 RELEASE org springframework bootorg springframework boot spring boot starter webspring boot starter web 精品文档 3欢迎下载 spring boot starter parentspring boot starter parent 作用作用 在在 pom xmlpom xml 中引入中引入 spring boot start parent springspring boot start parent spring 官方的解释叫什么官方的解释叫什么 staterstater poms poms 它可以提供它可以提供 dependencydependency management management 也就是说依赖管理 引入以后在申明其它也就是说依赖管理 引入以后在申明其它 dependencydependency 的时候就不需要的时候就不需要 versionversion 了 后面可以看到 了 后面可以看到 spring boot starter webspring boot starter web 作用作用 springwebspringweb 核心组件核心组件 spring boot maven pluginspring boot maven plugin 作用作用 如果我们要直接如果我们要直接 MainMain 启动启动 springspring 那么以下 那么以下 pluginplugin 必须要添加 否则是无法启动的 如果使用必须要添加 否则是无法启动的 如果使用 mavenmaven 的的 spring boot runspring boot run 的话是不需要此配置的 我在测试的时候 如果不配置下面的的话是不需要此配置的 我在测试的时候 如果不配置下面的 pluginplugin 也是直接在也是直接在 MainMain 中运行的 中运行的 2 32 3 编写 编写 HelloWorldHelloWorld 服务服务 创建 package 命名为 com itmayiedu controller 根据实际情况修改 创建 HelloController 类 内容如下 RestController RestController EnableAutoConfiguration EnableAutoConfiguration publicpublic classclass HelloControllerHelloController RequestMapping hello RequestMapping hello publicpublic StringString index index returnreturn Hello Hello World World publicpublic staticstatic voidvoid main String main String args args SpringApplication SpringApplication runrun HelloController class HelloController class args args 精品文档 4欢迎下载 2 42 4 RestController RestController 在上加上在上加上 RestControllerRestController 表示修饰该表示修饰该 ControllerController 所有的方法返回所有的方法返回 JSONJSON 格式格式 直接可以编直接可以编 写写 RestfulRestful 接口接口 2 52 5 EnableAutoConfiguration EnableAutoConfiguration 注解 作用在于让 Spring Boot 根据应用所声明的依赖来对 Spring 框架进行自动配置 这个注解告诉 Spring Boot 根据添加的 jar 依赖猜测你想如何配置 Spring 由于 spring boot starter web 添加了 Tomcat 和 Spring MVC 所以 auto configuration 将假定你正在开发一个 web 应用并 相应地对 Spring 进行设置 2 62 6 SpringApplication SpringApplication runrun HelloController class HelloController class args args 标识为启动类 2 6 1 SpringbootApplication SpringbootApplication 使用 SpringbootApplication 注解 可以解决根类或者配置类 我自己的说法 就是 main 所在类 头上注解过多的问题 一个 SpringbootApplication 相当于 Configuration EnableAutoConfiguration 和 ComponentScan 并具有他们的默认属性值 SpringBootApplication 等同于 Configuration EnableAutoConfiguration ComponentScanpublic class Application public static void main String args SpringApplication run Application class args 精品文档 5欢迎下载 2 72 7 SpringBootSpringBoot 启动方式启动方式 1 1 Springboot 默认端口号为 8080 RestController RestController EnableAutoConfiguration EnableAutoConfiguration publicpublic classclass HelloControllerHelloController RequestMapping hello RequestMapping hello publicpublic StringString index index returnreturn Hello Hello World World publicpublic staticstatic voidvoid main String main String args args SpringApplication SpringApplication runrun HelloController class HelloController class args args 启动主程序 打开浏览器访问 http localhost 8080 index 可以看到页面输出 Hello World 2 82 8 SpringBootSpringBoot 启动方式启动方式 2 2 ComponentScan basePackages com itmayiedu controller 控制器扫包范围 ComponentScan basePackages com itmayiedu controller EnableAutoConfiguration 精品文档 6欢迎下载 publicpublic classclass App publicpublic staticstatic voidvoid main String args SpringApplication run App classclass args 三 三 WebWeb 开发开发 3 13 1 静态资源访问 静态资源访问 在我们开发 Web 应用的时候 需要引用大量的 js css 图片等静态资源 默认配置 Spring Boot 默认提供静态资源目录位置需置于 classpath 下 目录名需符合如下规则 static public resources META INF resources 举例 我们可以在 src main resources 目录下创建 static 在该位置放置一个图片文件 启动程序后 尝试访问 http localhost 8080 D jpg 如能显示图片 配置成功 3 23 2 全局捕获异常 全局捕获异常 ExceptionHandler 表示拦截异常 ControllerAdvice 是 controller 的一个辅助类 最常用的就是作为全局异常处理的切面类 ControllerAdvice 可以指定扫描范围 精品文档 7欢迎下载 ControllerAdvice 约定了几种可行的返回值 如果是直接返回 model 类的话 需要使用 ResponseBody 进行 json 转换 o返回 String 表示跳到某个 view o返回 modelAndView o返回 model ResponseBody ControllerAdvice publicpublic classclass GlobalExceptionHandler ExceptionHandler RuntimeException classclass ResponseBody publicpublic Map exceptionHandler Map map newnew HashMap map put errorCode 101 map put errorMsg 系統错误 returnreturn map 3 33 3 渲染 渲染 WebWeb 页面页面 渲染 Web 页面 在之前的示例中 我们都是通过 RestController 来处理请求 所以返回的内容为 json 对象 那么如果 需要渲染 html 页面的时候 要如何实现呢 模板引擎 在动态 HTML 实现上 Spring Boot 依然可以完美胜任 并且提供了多种模板引擎的默认配置支持 所以在 推荐的模板引擎下 我们可以很快的上手开发动态网站 精品文档 8欢迎下载 Spring Boot 提供了默认配置的模板引擎主要有以下几种 Thymeleaf FreeMarker Velocity Groovy Mustache Spring Boot 建议使用这些模板引擎 避免使用 JSP 若一定要使用 JSP 将无法实现 Spring Boot 的多种 特性 具体可见后文 支持 JSP 的配置 当你使用上述模板引擎中的任何一个 它们默认的模板配置路径为 src main resources templates 当 然也可以修改这个路径 具体如何修改 可在后续各模板引擎的配置属性中查询并修改 3 43 4 使用使用 FreemarkerFreemarker 模板引擎渲染模板引擎渲染 webweb 视图视图 3 4 13 4 1 pompom 文件引入文件引入 org springframework boot spring boot starter freemarker 3 4 23 4 2 后台代码 后台代码 在 src main resources 创建一个 templates 文件夹 后缀为 ftl RequestMapping index RequestMapping index publicpublic StringString index Map String index MapObject map map map put name map put name 美丽的天使美丽的天使 returnreturn index index 精品文档 9欢迎下载 3 4 33 4 3 前台代码 前台代码 name 3 4 43 4 4 FreemarkerFreemarker 其他用法其他用法 RequestMapping index RequestMapping index publicpublic StringString index Map String index MapObject map map map put name map put name 蚂蚁课堂蚂蚁课堂 map put sex 1 map put sex 1 ListList userlistuserlist new new ArrayList ArrayList userlistuserlist add add 余胜军余胜军 userlistuserlist add add 张三张三 userlistuserlist add add 李四李四 精品文档 10欢迎下载 map put userlist map put userlist userlistuserlist returnreturn index index DOCTYPE head meta 首页首页 name name ifsex 1 男男 sex 2 女女 其他其他 listuser user user 精品文档 11欢迎下载 3 4 53 4 5 FreemarkerFreemarker 配置配置 新建 application properties 文件 FREEMARKER FreeMarkerAutoConfiguration spring freemarker allow request override false spring freemarker cache true spring freemarker check template location true spring freemarker charset UTF 8 spring freemarker content type text html spring freemarker expose request attributes false spring freemarker expose session attributes false spring freemarker expose spring macro helpers false spring freemarker prefix spring freemarker request context attribute spring freemarker settings spring freemarker suffix ftl spring freemarker template loader path classpath templates comma separated list spring freemarker view names whitelist of view names that can be resolved 精品文档 12欢迎下载 3 53 5 使用 使用 JSPJSP 渲染渲染 WebWeb 视图视图 3 5 13 5 1 pompom 文件引入以下依赖文件引入以下依赖 org springframework bootorg springframework boot spring boot starter parentspring boot starter parent 1 3 3 RELEASE1 3 3 RELEASE org springframework bootorg springframework boot spring boot starter webspring boot starter web org springframework bootorg springframework boot spring boot starter spring boot starter tomcattomcat org apache tomcat embedorg apache tomcat embed tomcattomcat embed embed jasperjasper 精品文档 13欢迎下载 3 5 23 5 2 在 在 application propertiesapplication properties 创建以下配置创建以下配置 spring mvc view prefix WEB INF jsp spring mvc view suffix jsp 3 5 33 5 3 后台代码 后台代码 Controller Controller publicpublic classclass IndexControllerIndexController RequestMapping index RequestMapping index publicpublic StringString index index returnreturn index index 精品文档 14欢迎下载 四 四 数据访问数据访问 4 14 1 springbootspringboot 整合整合使用使用 JdbcTemplateJdbcTemplate 4 1 14 1 1 pompom 文件引入文件引入 org springframework bootorg springframework boot spring boot starter parentspring boot starter parent 1 5 2 RELEASE1 5 2 RELEASE org springframework bootorg springframework boot spring boot starter spring boot starter jdbcjdbc mysqlmysql mysqlmysql connector java connector java 5 1 215 1 21 精品文档 15欢迎下载 org springframework bootorg springframework boot spring boot starter testspring boot starter test testtest org springframework bootorg springframework boot spring boot starter webspring boot starter web 4 1 24 1 2 application propertiesapplication properties 新增配置新增配置 spring datasource url jdbc mysql localhost 3306 test spring datasource username root spring datasource password root spring datasource driver class name com mysql jdbc Driver 4 1 34 1 3 UserServiceUserService 类类 Service Service publicpublic classclass UserServiceImplUserServiceImpl implementsimplements UserServiceUserService Autowired Autowired privateprivate JdbcTemplateJdbcTemplate jdbcTemplate jdbcTemplate publicpublic voidvoid createUser StringcreateUser String name name IntegerInteger age age 精品文档 16欢迎下载 System System outout println ssss println ssss jdbcTemplate update insertjdbcTemplate update insert intointo usersusers values null values null name name age age 4 1 44 1 4 AppApp 类类 ComponentScan basePackages ComponentScan basePackages com itmayiedu com itmayiedu EnableAutoConfiguration EnableAutoConfiguration publicpublic classclass AppApp publicpublic staticstatic voidvoid main String main String args args SpringApplication SpringApplication runrun App class App class args args 注意注意 spring boot starter parentspring boot starter parent 要在要在 1 51 5 以上以上 4 24 2 springbootspringboot 整合整合使用使用 mybatismybatis 4 2 14 2 1 pompom 文件引入文件引入 org springframework boot spring boot starter parent 1 3 2 RELEASE 精品文档 17欢迎下载 org springframework boot spring boot starter org springframework boot spring boot starter test test org mybatis spring boot mybatis spring boot starter 1 1 1 mysql mysql connector java 5 1 21 org springframework boot spring boot starter web 精品文档 18欢迎下载 4 2 24 2 2 配置文件引入 配置文件引入 spring datasource url jdbc mysql spring datasource url jdbc mysql localhostlocalhost 3306 test 3306 test spring datasource username rootspring datasource username root spring datasource password rootspring datasource password root spring datasource driver class name com mysql jdbc Driverspring datasource driver class name com mysql jdbc Driver 4 2 34 2 3 MapperMapper 代码代码 publicpublic interfaceinterface UserMapperUserMapper Select SELECT Select SELECT FROMFROM USERSUSERS WHEREWHERE NAMENAME name name UserUser findByName Param name findByName Param name StringString name name Insert INSERT Insert INSERT INTOINTO USERS NAME USERS NAME AGE AGE VALUES name VALUES name age age intint insert Param name insert Param name StringString name name Param age Param age IntegerInteger age age 4 2 44 2 4 启动方式 启动方式 ComponentScan basePackages com itmayiedu MapperScan basePackages com itmayiedu mapper 精品文档 19欢迎下载 SpringBootApplication publicpublic classclass App publicpublic staticstatic voidvoid main String args SpringApplication run App classclass args 4 34 3 springbootspringboot 整合整合使用使用 springjpaspringjpa 4 3 14 3 1 pompom 文件引入依赖文件引入依赖 org springframework boot spring boot starter parent 1 4 2 RELEASE org springframework boot spring boot starter data jpa mysql mysql connector java 精品文档 20欢迎下载 5 1 21 org springframework boot spring boot starter web 4 3 24 3 2 创建创建 UserUser 实体类实体类 Entity name users publicpublic classclass User Id GeneratedValue privateprivate Integer id Column privateprivate String name Column privateprivate Integer age get set方法 4 3 34 3 3 创建创建 UserDaoUserDao publicpublic interfaceinterface UserDao extendsextends JpaRepository 精品文档 21欢迎下载 4 3 44 3 4 创建创建 IndexControllerIndexController RestController RestController publicpublic classclass IndexControllerIndexController Autowired Autowired privateprivate UserDaoUserDao userDao userDao RequestMapping index RequestMapping index publicpublic StringString index Integerindex Integer id id UserUser findUserfindUser userDao findOne id userDao findOne id System System outout println findUser getName println findUser getName returnreturn success success 4 3 54 3 5 启动项目启动项目 ComponentScan basePackages com itmayiedu EnableJpaRepositories basePackages com itmayiedu dao EnableAutoConfiguration EntityScan basePackages com itmayiedu entity publicpublic classclass App publicpublic staticstatic voidvoid main String args SpringApplication run App classclass args 精品文档 22欢迎下载 4 44 4 springbootspringboot 整合多数据源整合多数据源 同学们思考下 你们在项目中有使用到多数据源吗 4 4 14 4 1 配置文件中新增两个数据源配置文件中新增两个数据源 spring datasource test1 driverClassName com mysql jdbc Driver spring datasource test1 url jdbc mysql localhost 3306 test01 useUnicode true build 精品文档 24欢迎下载 methodDesc methodDesc 功能描述功能描述 test1 test1 sqlsql会话工厂会话工厂 author author 余胜军余胜军 param param param param dataSourcedataSource param param return return param param throws throws ExceptionException createTime 2017 createTime 2017年年9 9月月1717日日 下午下午3 17 083 17 08 returnType param returnType param dataSourcedataSource returnType return returnType return returnType throws returnType throws ExceptionException SqlSessionFactorySqlSessionFactory copyright copyright 上海每特教育科技有限公司上海每特教育科技有限公司 QQ 644064779 QQ 644064779 Bean name Bean name test1SqlSessionFactory test1SqlSessionFactory Primary Primary publicpublic SqlSessionFactorySqlSessionFactory testSqlSessionFactory Qualifier test1DataSource testSqlSessionFactory Qualifier test1DataSource DataSourceDataSource dataSource dataSource throwsthrows ExceptionException SqlSessionFactoryBeanSqlSessionFactoryBean beanbean newnew SqlSessionFactoryBean SqlSessionFactoryBean bean setDataSource dataSource bean setDataSource dataSource bean setMapperLocations bean setMapperLocations newnew PathMatchingResourcePatternResolver getResources classpath mybatis PathMatchingResourcePatternResolver getResources classpath mybatis mappermapper test1 test1 xmlxml returnreturn bean getObject bean getObject 精品文档 25欢迎下载 methodDesc methodDesc 功能描述功能描述 test1 test1 事物管理事物管理 author author 余胜军余胜军 param param param param dataSourcedataSource param param return return param param throws throws ExceptionException createTime 2017 createTime 2017年年9 9月月1717日日 下午下午3 17 083 17 08 returnType param returnType param dataSourcedataSource returnType return returnType return returnType throws returnType throws ExceptionException SqlSessionFactorySqlSessionFactory copyright copyright 上海每特教育科技有限公司上海每特教育科技有限公司 QQ 644064779 QQ 644064779 Bean name Bean name test1TransactionManager test1TransactionManager Primary Primary publicpublic DataSourceTransactionManagerDataSourceTransactionManager testTransactionManager Qualifier test1DataSource testTransactionManager Qualifier test1DataSource DataSourceDataSource dataSource dataSource returnreturn newnew DataSourceTransactionManager dataSource DataSourceTransactionManager dataSource Bean name Bean name test1SqlSessionTemplate test1SqlSessionTemplate 精品文档 26欢迎下载 publicpublic SqlSessionTemplateSqlSessionTemplate testSqlSessionTemplate testSqlSessionTemplate Qualifier test1SqlSessionFactory Qualifier test1SqlSessionFactory SqlSessionFactorySqlSessionFactory sqlSessionFactory sqlSessionFactory throwsthrows ExceptionException returnreturn newnew SqlSessionTemplate sqlSessionFactory SqlSessionTemplate sqlSessionFactory 4 4 24 4 2 创建分包创建分包MapperMapper publicpublic interfaceinterface User1Mapper Insert insert into users values null name age publicpublic intint addUser Param name String name Param age Integer age 4 4 34 4 3 启动项目启动项目 ComponentScan basePackages ComponentScan basePackages com itmayiedu com itmayiedu EnableAutoConfiguration EnableAutoConfiguration publicpublic classclass AppApp publicpublic staticstatic voidvoid main String main String args args SpringApplication SpringApplication runrun App class App class args args 精品文档 27欢迎下载 No qualifying bean of type javax sql DataSource is defined expected single matching bean but found 2 test1DataSource test2DataSource 五 五 事物管理事物管理 5 1 1springboot5 1 1springboot 整合事物管理整合事物管理 springboot 默认集成事物 只主要在方法上加上 Transactional 即可 5 1 2SpringBoot5 1 2SpringBoot 分布式事物管理分布式事物管理 使用 springboot jta atomikos 分布式事物管理 5 1 2 15 1 2 1 新增配置文件信息新增配置文件信息 org springframework bootorg springframework boot spring boot starter spring boot starter jtajta atomikosatomikos 5 1 2 25 1 2 2 新增配置文件信息新增配置文件信息 MysqlMysql 1 1 mysql datasource test urlmysql datasource test url jdbc mysql jdbc mysql localhostlocalhost 3306 test01 useUnicode truecom itmayiedu config importimport org springframework boot context properties ConfigurationProperties org springframework boot context properties ConfigurationProperties ConfigurationProperties prefix ConfigurationProperties prefix mysql datasource test mysql datasource test publicpublic classclass DBConfig1DBConfig1 privateprivate StringString url url privateprivate StringString username username privateprivate StringString passwordpassword privateprivate intint minPoolSize minPoolSize privateprivate intint maxPoolSize maxPoolSize privateprivate intint maxLifetime maxLifetime privateprivate intint borrowConnectionTimeout borrowConnectionTimeout privateprivate intint loginTimeout loginTimeout privateprivate intint maintenanceInterval maintenanceInterval privateprivate intint maxIdleTime maxIdleTime privateprivate StringString testQuery testQuery 精品文档 30欢迎下载 packagepackage com itmayiedu config com itmayiedu config importimport org springframework boot context properties ConfigurationProperties org springframework boot context properties ConfigurationProperties ConfigurationProperties prefix ConfigurationProperties prefix mysql datasource test1 mysql datasource test1 publicpublic classclass DBConfig2DBConfig2 privateprivate StringString url url privateprivate StringString username username privateprivate StringString passwordpassword privateprivate intint minPoolSize minPoolSize privateprivate intint maxPoolSize maxPoolSize privateprivat

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

最新文档

评论

0/150

提交评论