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

下载本文档

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

文档简介

精选文库SpringBoot一、 Spring介绍1.1、SpringBoot简介在您第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.2、系统要求:Java 7及以上Spring Framework 4.1.5及以上本文采用Java 1.8.0_73、Spring Boot 1.3.2调试通过。二、快速入门2.1、创建一个Maven工程名为”springboot-helloworld” 类型为Jar工程项目2.2、pom文件引入依赖org.springframework.bootspring-boot-starter-parent1.3.3.RELEASE org.springframework.bootspring-boot-starter-webspring-boot-starter-parent作用在pom.xml中引入spring-boot-start-parent,spring官方的解释叫什么stater poms,它可以提供dependency management,也就是说依赖管理,引入以后在申明其它dependency的时候就不需要version了,后面可以看到。spring-boot-starter-web作用springweb 核心组件spring-boot-maven-plugin作用如果我们要直接Main启动spring,那么以下plugin必须要添加,否则是无法启动的。如果使用maven的spring-boot:run的话是不需要此配置的。(我在测试的时候,如果不配置下面的plugin也是直接在Main中运行的。)2.3、编写HelloWorld服务创建package命名为com.itmayiedu.controller(根据实际情况修改)创建HelloController类,内容如下RestControllerEnableAutoConfigurationpublic class HelloController RequestMapping(/hello)public String index() return Hello World;public static void main(String args) SpringApplication.run(HelloController.class, args);2.4、RestController在上加上RestController 表示修饰该Controller所有的方法返回JSON格式,直接可以编写Restful接口2.5、EnableAutoConfiguration注解:作用在于让 Spring Boot 根据应用所声明的依赖来对 Spring 框架进行自动配置 这个注解告诉Spring Boot根据添加的jar依赖猜测你想如何配置Spring。由于spring-boot-starter-web添加了Tomcat和Spring MVC,所以auto-configuration将假定你正在开发一个web应用并相应地对Spring进行设置。2.6 SpringApplication.run(HelloController.class, args); 标识为启动类2.6.1SpringbootApplication使用SpringbootApplication注解 可以解决根类或者配置类(我自己的说法,就是main所在类)头上注解过多的问题,一个SpringbootApplication相当于Configuration,EnableAutoConfiguration和ComponentScan并具有他们的默认属性值SpringBootApplication/等同于 Configuration EnableAutoConfiguration ComponentScanpublicclassApplication publicstaticvoidmain(String args) SpringApplication.run(Application.class, args);2.7、SpringBoot启动方式1Springboot默认端口号为8080RestControllerEnableAutoConfigurationpublic class HelloController RequestMapping(/hello)public String index() return Hello World;public static void main(String args) SpringApplication.run(HelloController.class, args);启动主程序,打开浏览器访问http:/localhost:8080/index,可以看到页面输出Hello World2.8、SpringBoot启动方式2ComponentScan(basePackages = com.itmayiedu.controller)-控制器扫包范围ComponentScan(basePackages = com.itmayiedu.controller)EnableAutoConfigurationpublic class App public static void main(String args) SpringApplication.run(App.class, args);三、 Web开发3.1、静态资源访问在我们开发Web应用的时候,需要引用大量的js、css、图片等静态资源。默认配置Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:/static/public/resources/META-INF/resources举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件。启动程序后,尝试访问http:/localhost:8080/D.jpg。如能显示图片,配置成功。3.2、全局捕获异常ExceptionHandler 表示拦截异常 ControllerAdvice 是 controller 的一个辅助类,最常用的就是作为全局异常处理的切面类 ControllerAdvice 可以指定扫描范围 ControllerAdvice 约定了几种可行的返回值,如果是直接返回 model 类的话,需要使用 ResponseBody 进行 json 转换o 返回 String,表示跳到某个 viewo 返回 modelAndViewo 返回 model + ResponseBodyControllerAdvicepublic class GlobalExceptionHandler ExceptionHandler(RuntimeException.class)ResponseBodypublic Map exceptionHandler() Map map = new HashMap();map.put(errorCode, 101);map.put(errorMsg, 系統错误!);return map;3.3、渲染Web页面渲染Web页面在之前的示例中,我们都是通过RestController来处理请求,所以返回的内容为json对象。那么如果需要渲染html页面的时候,要如何实现呢?模板引擎在动态HTML实现上Spring Boot依然可以完美胜任,并且提供了多种模板引擎的默认配置支持,所以在推荐的模板引擎下,我们可以很快的上手开发动态网站。Spring Boot提供了默认配置的模板引擎主要有以下几种: Thymeleaf FreeMarker Velocity Groovy MustacheSpring Boot建议使用这些模板引擎,避免使用JSP,若一定要使用JSP将无法实现Spring Boot的多种特性,具体可见后文:支持JSP的配置当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates。当然也可以修改这个路径,具体如何修改,可在后续各模板引擎的配置属性中查询并修改。3.4、使用Freemarker模板引擎渲染web视图3.4.1、pom文件引入:org.springframework.bootspring-boot-starter-freemarker3.4.2、后台代码在src/main/resources/创建一个templates文件夹,后缀为*.ftlRequestMapping(/index)public String index(Map map) map.put(name,美丽的天使.);return index;3.4.3、前台代码 $name 3.4.4、Freemarker其他用法RequestMapping(/index)public String index(Map map) map.put(name,#蚂蚁课堂#); map.put(sex,1); List userlist=new ArrayList(); userlist.add(余胜军); userlist.add(张三); userlist.add(李四); map.put(userlist,userlist); return index;首页 $name 男 女 其他 $user 3.4.5、Freemarker配置新建perties文件#FREEMARKER (FreeMarkerAutoConfiguration)#spring.freemarker.allow-request-override=falsespring.freemarker.cache=truespring.freemarker.check-template-location=truespring.freemarker.charset=UTF-8spring.freemarker.content-type=text/htmlspring.freemarker.expose-request-attributes=falsespring.freemarker.expose-session-attributes=falsespring.freemarker.expose-spring-macro-helpers=false#spring.freemarker.prefix=#spring.freemarker.request-context-attribute=#spring.freemarker.settings.*=spring.freemarker.suffix=.ftlspring.freemarker.template-loader-path=classpath:/templates/#comma-separated list#spring.freemarker.view-names= # whitelist of view names that can be resolved3.5、使用JSP渲染Web视图3.5.1、pom文件引入以下依赖org.springframework.bootspring-boot-starter-parent1.3.3.RELEASEorg.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-tomcatorg.apache.tomcat.embedtomcat-embed-jasper3.5.2、在perties创建以下配置spring.mvc.view.prefix=/WEB-INF/jsp/spring.mvc.view.suffix=.jsp3.5.3、后台代码Controllerpublic class IndexController RequestMapping(/index)public String index() return index;四、 数据访问4.1、springboot整合使用JdbcTemplate4.1.1 pom文件引入org.springframework.bootspring-boot-starter-parent1.5.2.RELEASEorg.springframework.bootspring-boot-starter-jdbcmysqlmysql-connector-java5.1.21org.springframework.bootspring-boot-starter-testtestorg.springframework.bootspring-boot-starter-web4.1.2 perties新增配置spring.datasource.url=jdbc:mysql:/localhost:3306/testspring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driver4.1.3 UserService类Servicepublic class UserServiceImpl implements UserService Autowiredprivate JdbcTemplate jdbcTemplate;public void createUser(String name, Integer age) System.out.println(ssss);jdbcTemplate.update(insert into users values(null,?,?);, name, age);4.1.4 App类ComponentScan(basePackages = com.itmayiedu)EnableAutoConfigurationpublic class App public static void main(String args) SpringApplication.run(App.class, args);注意: spring-boot-starter-parent要在1.5以上4.2、springboot整合使用mybatis4.2.1、pom文件引入org.springframework.bootspring-boot-starter-parent1.3.2.RELEASE org.springframework.bootspring-boot-starterorg.springframework.bootspring-boot-starter-testtestorg.mybatis.spring.bootmybatis-spring-boot-starter1.1.1mysqlmysql-connector-java5.1.21org.springframework.bootspring-boot-starter-web4.2.2、配置文件引入spring.datasource.url=jdbc:mysql:/localhost:3306/testspring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driver4.2.3、Mapper代码public interface UserMapper Select(SELECT * FROM USERS WHERE NAME = #name)User findByName(Param(name) String name);Insert(INSERT INTO USERS(NAME, AGE) VALUES(#name, #age)int insert(Param(name) String name, Param(age) Integer age);4.2.4、启动方式ComponentScan(basePackages = com.itmayiedu)MapperScan(basePackages = com.itmayiedu.mapper)SpringBootApplicationpublic class App public static void main(String args) SpringApplication.run(App.class, args);4.3、springboot整合使用springjpa4.3.1 pom文件引入依赖org.springframework.bootspring-boot-starter-parent1.4.2.RELEASEorg.springframework.bootspring-boot-starter-data-jpamysqlmysql-connector-java5.1.21org.springframework.bootspring-boot-starter-web4.3.2 创建User实体类Entity(name = users)public class User IdGeneratedValueprivate Integer id;Columnprivate String name;Columnprivate Integer age; / .get/set方法4.3.3 创建UserDaopublic interface UserDao extends JpaRepository 4.3.4 创建IndexControllerRestControllerpublic class IndexController Autowiredprivate UserDao userDao;RequestMapping(/index)public String index(Integer id) User findUser = userDao.findOne(id);System.out.println(findUser.getName();return success;4.3.5 启动项目ComponentScan(basePackages = com.itmayiedu )EnableJpaRepositories(basePackages = com.itmayiedu.dao)EnableAutoConfigurationEntityScan(basePackages = com.itmayiedu.entity)public class App public static void main(String args) SpringApplication.run(App.class, args);4.4、springboot整合多数据源同学们思考下,你们在项目中有使用到多数据源吗?4.4.1配置文件中新增两个数据源spring.datasource.test1.driverClassName = com.mysql.jdbc.Driverspring.datasource.test1.url = jdbc:mysql:/localhost:3306/test01?useUnicode=true&characterEncoding=utf-8spring.datasource.test1.username = rootspring.datasource.test1.password = rootspring.datasource.test2.driverClassName = com.mysql.jdbc.Driverspring.datasource.test2.url = jdbc:mysql:/localhost:3306/test02?useUnicode=true&characterEncoding=utf-8spring.datasource.test2.username = rootspring.datasource.test2.password = root4.4.2配置文件中新增两个数据源Configuration / 注册到springboot容器中MapperScan(basePackages = com.itmayiedu.user1, sqlSessionFactoryRef = test1SqlSessionFactory)public class DataSource1Config /* * * methodDesc: 功能描述:(配置test1数据库) * author: 余胜军 * param: return * createTime:2017年9月17日 下午3:16:44 * returnType:return DataSource * copyright:上海每特教育科技有限公司 * QQ:644064779 */Bean(name = test1DataSource)PrimaryConfigurationProperties(prefix = spring.datasource.test1)public DataSource testDataSource() return DataSourceBuilder.create().build();/* * * methodDesc: 功能描述:(test1 sql会话工厂) * author: 余胜军 * param: param * dataSource * param: return * param: throws * Exception * createTime:2017年9月17日 下午3:17:08 * returnType:param dataSource * returnType:return * returnType:throws Exception SqlSessionFactory * copyright:上海每特教育科技有限公司 * QQ:644064779 */Bean(name = test1SqlSessionFactory)Primarypublic SqlSessionFactory testSqlSessionFactory(Qualifier(test1DataSource) DataSource dataSource)throws Exception SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(dataSource);/bean.setMapperLocations(/new PathMatchingResourcePatternResolver().getResources(classpath:mybatis/mapper/test1/*.xml);return bean.getObject();/* * * methodDesc: 功能描述:(test1 事物管理) * author: 余胜军 * param: param * dataSource * param: return * param: throws * Exception * createTime:2017年9月17日 下午3:17:08 * returnType:param dataSource * returnType:return * returnType:throws Exception SqlSessionFactory * copyright:上海每特教育科技有限公司 * QQ:644064779 */Bean(name = test1TransactionManager)Primarypublic DataSourceTransactionManager testTransactionManager(Qualifier(test1DataSource) DataSource dataSource) return new DataSourceTransactionManager(dataSource);Bean(name = test1SqlSessionTemplate)public SqlSessionTemplate testSqlSessionTemplate(Qualifier(test1SqlSessionFactory) SqlSessionFactory sqlSessionFactory) throws Exception return new SqlSessionTemplate(sqlSessionFactory);4.4.2创建分包Mapper public interface User1Mapper Insert(insert into users values(null,#name,#age);)public int addUser(Param(name) String name, Param(age) Integer age);4.4.3启动项目ComponentScan(basePackages = com.itmayiedu)EnableAutoConfigurationpublic class App public static void main(String args) SpringApplication.run(App.class, args);No qualifying bean of type javax.sql.DataSource is defined: expected single matching bean but found 2: test1DataSource,test2DataSource五、 事物管理5.1.1springboot整合事物管理 springboot默认集成事物,只主要在方法上加上Transactional即可5.1.2SpringBoot分布式事物管理使用springboot+jta+atomikos分布式事物管理新增配置文件信息org.springframework.bootspring-boot-starter-jta-atomikos新增配置文件信息# Mysql 1mysql.datasource.test.url = jdbc:mysql:/localhost:3306/test01?useUnicode=true&characterEncoding=utf-8mysql.datasource.test.username = rootmysql.datasource.test.password = rootmysql.datasource.test.minPoolSize = 3mysql.datasource.test.maxPoolSize = 25mysql.datasource.test.maxLifetime = 20000mysql.datasource.test.borrowConnectionTimeout = 30mysql.datasource.test.loginTimeout = 30mysql.datasource.test.maintenanceInterval = 60mysql.datasource.test.maxIdleTime = 60mysql.datasource.test.testQuery = select 1# Mysql 2mysql.datasource.test2.url =jdbc:mysql:/localhost:3306/test02?useUnicode=true&characterEncoding=utf-8mysql.datasource.test2.username =rootmysql.datasource.test2.password =rootmysql.datasource.test2.minPoolSize = 3mysql.datasource.test2.maxPoolSize = 25mysql.datasource.test2.maxLifetime = 20000mysql.datasource.test2.borrowConnectionTimeout = 30mysql.datasource.test2.loginTimeout = 30mysql.datasource.test2.maintenanceInterval = 60mysql.datasource.test2.maxIdleTime = 60mysql.datasource.test2.testQuery = select 读取配置文件信息package com.itmayiedu.config;import perties.ConfigurationProperties;ConfigurationProperties(prefix = mysql.datasource.test)public class DBConfig1 private String url;private String username;private String password;private int minPoolSize;private int maxPoolSize;private int maxLifetime;private int borrowConnectionTimeout;private int loginTimeout;private int maintenanceInterval;private int maxIdleTime;private String testQuery;package com.itmayiedu.config;import perties.ConfigurationProperties;ConfigurationProperties(prefix = mysql.datasource.test1)public class DBConfig2 private String url;private String username;private String password;private int minPoolSize;private int maxPoolSize;private int maxLifetime;private int borrowConnectionTimeout;private int loginTimeout;private int maintenanceInterval;private int maxIdleTime;private St

温馨提示

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

评论

0/150

提交评论