



版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、SpringBoot一、 Spring介紹1.1 、 SpringBoot簡(jiǎn)介在您第 1 次接觸和學(xué)習(xí) Spring框架的時(shí)候,是否因?yàn)槠浞彪s的配置而退卻了?在你第n 次使用 Spring 框架的時(shí)候,是否覺得一堆反復(fù)黏貼的配置有一些厭煩?那么您就不妨來試試使用Spring Boot 來讓你更易上手,更簡(jiǎn)單快捷地構(gòu)建 Spring 應(yīng)用!Spring Boot 讓我們的 Spring應(yīng)用變的更輕量化。比如:你可以僅僅依靠一個(gè)Java 類來運(yùn)行一個(gè) Spring引用。你也可以打包你的應(yīng)用為jar 并通過使用 java -jar來運(yùn)行你的 Spring Web 應(yīng)用。Spring Boot 的主要
2、優(yōu)點(diǎn):為所有 Spring 開發(fā)者更快的入門開箱即用,提供各種默認(rèn)配置來簡(jiǎn)化項(xiàng)目配置內(nèi)嵌式容器簡(jiǎn)化 Web項(xiàng)目沒有冗余代碼生成和XML配置的要求本章主要目標(biāo)完成Spring Boot基礎(chǔ)項(xiàng)目的構(gòu)建,并且實(shí)現(xiàn)一個(gè)簡(jiǎn)單的Http請(qǐng)求處理,通過這個(gè)例子對(duì)Spring Boot有一個(gè)初步的了解,并體驗(yàn)其結(jié)構(gòu)簡(jiǎn)單、開發(fā)快速的特性。1.2 、系統(tǒng)要求:Java 7及以上本文采用及以上、調(diào)試通過。二、快速入門2.1 、創(chuàng)建一個(gè)Maven 工程名為” springboot-helloworld” 類型為 Jar 工程項(xiàng)目2.2 、 pom文件引入依賴<parent ></ groupId &
3、gt;<artifactId>spring-boot-starter-parent</ artifactId<version</ parent ><dependencies ><! SpringBoot web組件 -><dependency ></ groupId ><artifactId>spring-boot-starter-web</ artifactId</ dependency ></ dependencies >>>spring-boot-st
4、arter-parent作用在 pom.xml 中引入 spring-boot-start-parent,spring官方的解釋叫什么stater poms,它可以提供也就是說依賴管理,引入以后在申明其它dependency 的時(shí)候就不需要version了,后面可以看到。dependency management,spring-boot-starter-web作用springweb核心組件spring-boot-maven-plugin作用如果我們要直接 Main 啟動(dòng) spring ,那么以下 plugin 必須要添加, 否則是無法啟動(dòng)的。 如果使用 maven 的話是不需要此配置的。(我在
5、測(cè)試的時(shí)候,如果不配置下面的 plugin 也是直接在 Main 中運(yùn)行的。)的spring-boot:run2.3 、編寫 HelloWorld服務(wù)創(chuàng)建創(chuàng)建package 命名為 .itmayiedu.controllerHelloController類,內(nèi)容如下(根據(jù)實(shí)際情況修改)RestControllerEnableAutoConfigurationpublicclassHelloController RequestMapping( "/hello")publicString index() return"Hello World"publicst
6、aticvoid main(Stringargs ) SpringApplication.run (HelloController.class ,args );2.4 、 RestController在上加上RestController表示修飾該Controller所有的方法返回JSON格式 , 直接可以編寫Restful接口2.5 、 EnableAutoConfiguration注解 : 作用在于讓Spring Boot根據(jù)應(yīng)用所聲明的依賴來對(duì)這個(gè)注解告訴Spring Boot根據(jù)添加的jarspring-boot-starter-web添加了 Tomcat 和 Spring MVC ,所
7、以個(gè) web 應(yīng)用并相應(yīng)地對(duì)Spring進(jìn)行設(shè)置。Spring框架進(jìn)行自動(dòng)配置依賴猜 測(cè) 你想 如何配 置Spring 。 由于auto-configuration將假定你正在開發(fā)一2.6SpringApplication.run(HelloController.class ,args );標(biāo)識(shí)為啟動(dòng)類SpringbootApplication使用 SpringbootApplication注解可以解決根類或者配置類(我自己的說法, 就是 main 所在類)頭上注解過多的問題,一個(gè)SpringbootApplication相當(dāng)于 Configuration,EnableAutoConfigur
8、ation和 ponentScan 并具有他們的默認(rèn)屬性值SpringBootApplication/ 等同于Configuration EnableAutoConfiguration ponentScanpublicclassApplication publicstaticvoidmain(String args) SpringApplication.run(Application.class , args);2.7 、 SpringBoot啟動(dòng)方式 1Springboot默認(rèn)端口號(hào)為8080RestControllerEnableAutoConfigurationpublicclass H
9、elloController RequestMapping( "/hello" public String index() return "Hello World");publicstatic void main(String args ) SpringApplication. run (HelloController.class ,args );啟動(dòng)主程序,打開瀏覽器訪問http:/localhost:8080/index,可以看到頁面輸出Hello World2.8 、 SpringBoot啟動(dòng)方式2ponentScan(basePackages =
10、 ponentScan(basePackages =".itmayiedu.controller"".itmayiedu.controller")-)控制器掃包范圍EnableAutoConfigurationpublicclassApp publicstaticvoidmain(Stringargs ) SpringApplication.run (App. class ,args );三、 Web 開發(fā)3.1 、靜態(tài)資源訪問在我們開發(fā)Web應(yīng)用的時(shí)候,需要引用大量的js 、 css 、圖片等靜態(tài)資源。默認(rèn)配置Spring Boot默認(rèn)提供靜態(tài)資源目錄
11、位置需置于classpath下,目錄名需符合如下規(guī)則:/static/public/resources/META-INF/resources舉例:我們可以在src/main/resources/嘗試訪問 http:/localhost:8080/D.jpg目錄下創(chuàng)建static,在該位置放置一個(gè)圖片文件。啟動(dòng)程序后,。如能顯示圖片,配置成功。3.2 、全局捕獲異常ExceptionHandler表示攔截異常ControllerAdvice是 controller的一個(gè)輔助類,最常用的就是作為全局異常處理的切面類ControllerAdvice可以指定掃描范圍ControllerAdvice約定
12、了幾種可行的返回值,如果是直接返回model類的話,需要使用ResponseBody進(jìn)行 json轉(zhuǎn)換o返回 String,表示跳到某個(gè)viewo返回modelAndViewo返回model + ResponseBodyControllerAdvicepublicclassGlobalExceptionHandler ExceptionHandler (RuntimeException.class )ResponseBodypublicMap<String, Object> exceptionHandler() Map<String, Object>map=new Ha
13、shMap<String, Object>();map.put("errorCode","101" );map.put("errorMsg" ," 系統(tǒng)錯(cuò)誤 !" );returnmap;3.3 、渲染 Web頁面渲染 Web頁面在之前的示例中,我們都是通過RestController來處理請(qǐng)求,所以返回的內(nèi)容為json對(duì)象。那么如果需要渲染 html 頁面的時(shí)候,要如何實(shí)現(xiàn)呢?模板引擎在動(dòng)態(tài) HTML實(shí)現(xiàn)上 Spring Boot 依然可以完美勝任,并且提供了多種模板引擎的默認(rèn)配置支持,所以在推薦的模
14、板引擎下,我們可以很快的上手開發(fā)動(dòng)態(tài)網(wǎng)站。Spring Boot提供了默認(rèn)配置的模板引擎主要有以下幾種:ThymeleafFreeMarkerVelocityGroovyMustacheSpring Boot 建議使用這些模板引擎,避免使用 JSP,若一定要使用 JSP將無法實(shí)現(xiàn) Spring Boot 的多種特性,具體可見后文:支持 JSP 的配置src/main/resources/templates然也可以修改這個(gè)路徑,具體如何修改,可在后續(xù)各模板引擎的配置屬性中查詢并修改。3.4 、使用Freemarker模板引擎渲染web 視圖、pom文件引入 :<!-引入 freeMarke
15、r的依賴包. -><dependency ></ groupId ><artifactId>spring-boot-starter-freemarker</ artifactId></ dependency >、后臺(tái)代碼在 src/main/resources/創(chuàng)建一個(gè) templates 文件夾 , 后綴為 *.ftlRequestMapping ( "/index")publicString index(Map<String, Object>map) map.put("name&qu
16、ot; , " 美麗的天使.");return"index"、前臺(tái)代碼<!DOCTYPE html><html><head lang="en"><meta charset="UTF-8" /><title></title></head><body>$name</body></html>、Freemarker其他用法RequestMapping ( "/index")public
17、 String index(Map<String, Object>map) map.put("name" , "# 螞蟻課堂 #" );map.put("sex",1);List<String>userlist =new ArrayList<String>();userlist.add( "余勝軍 " );userlist.add( "張三 " );userlist.add( "李四 " );map.put("userlist&q
18、uot;, userlist );return"index"<!DOCTYPE html><html><head lang="en"><meta charset="UTF-8" /><title>首頁 </title></head><body>$name<#if sex=1>男<#elseif sex=2>女<#else>其他</#if><#list userlist as user&g
19、t;$user</#list></body></html>、Freemarker配置新建 perties文件#FREEMARKER (FreeMarkerAutoConfiguration)#ma-separated list3.5 、使用 JSP 渲染 Web視圖、pom文件引入以下依賴<parent ></ groupId ><artifactId>spring-boot-starter-parent</ artifactId></ parent ><depe
20、ndencies ><!- SpringBoot核心組件-><dependency></ groupId ><artifactId>spring-boot-starter-web</ artifactId</ dependency><dependency></ groupId ><artifactId>spring-boot-starter-tomcat</ artifactId</ dependency><dependency></ groupId
21、><artifactId>tomcat-embed-jasper</ artifactId></ dependencies >>>、在 perties創(chuàng)建以下配置/WEB-INF/jsp/.jsp、后臺(tái)代碼ControllerpublicclassIndexController RequestMapping ( "/index")publicString index() return"index"四、數(shù)據(jù)訪問4.1 、 springboot整合使用 JdbcTemplat
22、e文件引入<parent ></ groupId ><artifactId>spring-boot-starter-parent</ artifactId><version></ parent ><dependencies><dependency ></ groupId ><artifactId>spring-boot-starter-jdbc</ artifactId</ dependency ><dependency ><groupId
23、 >mysql </ groupId ><artifactId>mysql-connector-java</ artifactId><version</ version></ dependency >><dependency ><artifactId>spring-boot-starter-test<scope >test </ scope ></ dependency ><dependency ><artifactId>spring
24、-boot-starter-web</ dependency ></ dependencies></ groupId > </ artifactId </ groupId > </ artifactId>>新增配置jdbc:mysql:/localhost:3306/testrootroot類ServicepublicclassUserServiceImplimplementsUserService AutowiredprivateJdbcTemplatejdbcTemplate;publicvoidcreateUser(
25、Stringname, Integerage) System. out .println("ssss");jdbcTemplate.update("insert into users values(null,?,?);",name,age);4.1.4 App類ponentScan(basePackages =".itmayiedu")EnableAutoConfigurationpublic class App publicstaticvoid main(Stringargs ) SpringApplication.run (App
26、. class , args );注意 : spring-boot-starter-parent要在 1.5以上4.2 、 springboot整合使用 mybatis4.2.1 、 pom文件引入<parent><groupId>org.springframework.boot</ groupId ><artifactId>spring-boot-starter-parent</ artifactId><version>1.3.2.RELEASE</ version><relativePath/>
27、 <!- lookup parent from repository -></ parent ><dependencies ><dependency ></ groupId ><artifactId>spring-boot-starter</ artifactId></ dependency ><dependency ></ groupId ><artifactId>spring-boot-starter-test</ artifactId<scope
28、>test </ scope ></ dependency ><dependency ><artifactId>mybatis-spring-boot-starter</artifactId></ dependency ><dependency ><groupId >mysql </ groupId ><artifactId>mysql-connector-java</ artifactId><version></ dependency &
29、gt;<dependency ></ groupId ><artifactId>spring-boot-starter-web</ artifactId</ dependency >>></ dependencies>、配置文件引入jdbc:mysql:/localhost:3306/testrootroot、 Mapper代碼publicinterfaceUserMapper Select ( "SELECT * FROM USERS WHERE NAME = #name" )User find
30、ByName(Param( "name" ) Stringname);Insert ( "INSERT INTO USERS(NAME, AGE) VALUES(#name, #age)"intinsert(Param( "name" ) Stringname,Param( "age" ) Integer)age );、啟動(dòng)方式ponentScan(basePackages =".itmayiedu")MapperScan(basePackages =".itmayiedu.mappe
31、r")SpringBootApplicationpublicclassApp publicstaticvoidmain(Stringargs ) SpringApplication.run (App. class ,args );4.3 、 springboot整合使用 springjpa文件引入依賴<parent ></ groupId ><artifactId>spring-boot-starter-parent</ artifactId></ parent ><dependencies ><depen
32、dency></ groupId ><artifactId>spring-boot-starter-data-jpa</ artifactId</ dependency><dependency><groupId >mysql</ groupId ><artifactId>mysql-connector-java</ artifactId></ dependency><dependency></ groupId ><artifactId>sp
33、ring-boot-starter-web</ artifactId></ dependency></ dependencies >>創(chuàng)建 User 實(shí)體類Entity (name ="users")publicclassUser IdGeneratedValueprivateIntegerid ;ColumnprivateStringname;ColumnprivateIntegerage;/ .get/set方法創(chuàng)建 UserDaopublicinterfaceUserDaoextends JpaRepository<Us
34、er, Integer> 創(chuàng)建 IndexControllerRestControllerpublic classIndexController AutowiredprivateUserDao userDao ;RequestMapping ( "/index");publicString index(Integerid ) UserfindUser=userDao .findOne( idSystem. out .println(findUser .getName();return"success"啟動(dòng)項(xiàng)目ponentScan(basePacka
35、ges = ".itmayiedu")EnableJpaRepositories(basePackages =".itmayiedu.dao"EnableAutoConfigurationEntityScan(basePackages =".itmayiedu.entity")publicclassApp publicstaticvoidmain(Stringargs ) SpringApplication.run (App. class ,args );)4.4 、 springboot整合多數(shù)據(jù)源同學(xué)們思考下,你們?cè)陧?xiàng)目中有使用到
36、多數(shù)據(jù)源嗎?配置文件中新增兩個(gè)數(shù)據(jù)源spring.datasource.test1.driverClassName =.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 =
37、.mysql.jdbc.Driverspring.datasource.test2.url =jdbc:mysql:/localhost:3306/test02?useUnicode=true&characterEncoding=utf-8spring.datasource.test2.username =rootspring.datasource.test2.password =root配置文件中新增兩個(gè)數(shù)據(jù)源Configuration/注冊(cè)到 springboot容器中MapperScan(basePackages =".itmayiedu.user1", sq
38、lSessionFactoryRef ="test1SqlSessionFactory")publicclassDataSource1Config /*methodDesc:功能描述 :( 配置 test1數(shù)據(jù)庫 )* author : 余勝軍* param: return* createTime :2017 年 9月 17 日 下午 3:16:44* returnType :return DataSource* copyright : 上海每特教育科技有限公司* :644064779*/Bean(name ="test1DataSource")Prim
39、aryConfigurationProperties(prefix =publicDataSource testDataSource() returnDataSourceBuilder.create ().build();)/*methodDesc:功能描述 :(test1 sql會(huì)話工廠 )* author : 余勝軍* param: param* dataSource* param: return* param: throws* Exception* createTime :2017 年 9月 17 日 下午 3:17:08* returnType :param dataSource* r
40、eturnType :return* returnType :throws Exception SqlSessionFactory* copyright : 上海每特教育科技有限公司* :644064779*/Bean(name ="test1SqlSessionFactory")PrimarypublicSqlSessionFactory testSqlSessionFactory(Qualifier( "test1DataSource") DataSourcedataSourcethrowsException SqlSessionFactoryBea
41、nbean =new SqlSessionFactoryBean();bean.setDataSource(dataSource );)/ bean.setMapperLocations(/new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"); return bean .getObject();/*methodDesc:功能描述 :(test1事物管理 )* author : 余勝軍* param: param* dataSource* p
42、aram: return* param: throws* Exception* createTime :2017 年 9月 17 日 下午 3:17:08* returnType :param dataSource* returnType :return* returnType :throws Exception SqlSessionFactory* copyright : 上海每特教育科技有限公司* :644064779*/Bean(name ="test1TransactionManager")PrimarypublicDataSourceTransactionMana
43、ger testTransactionManager(Qualifier( "test1DataSource") DataSourcedataSource ) returnnew DataSourceTransactionManager(dataSource);Bean(name ="test1SqlSessionTemplate")publicSqlSessionTemplate testSqlSessionTemplate(Qualifier ( "test1SqlSessionFactory") SqlSessionFactor
44、ysqlSessionFactory)throws Exception returnnew SqlSessionTemplate(sqlSessionFactory);創(chuàng)建分包 MapperpublicinterfaceUser1Mapper Insert ( "insert into users values(null,#name,#age);")publicintaddUser( Param( "name") Stringname,Param( "age" ) Integerage);啟動(dòng)項(xiàng)目ponentScan(basePack
45、ages =".itmayiedu")EnableAutoConfigurationpublicclassApp publicstaticvoidmain(Stringargs ) SpringApplication.run (App. class,args );五、事物管理整合事物管理springboot默認(rèn)集成事物 , 只主要在方法上加上Transactional即可分布式事物管理使用 springboot+jta+atomikos分布式事物管理新增配置文件信息<dependency ></ groupId><artifactId>s
46、pring-boot-starter-jta-atomikos</ artifactId></ dependency >新增配置文件信息# 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.d
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 助動(dòng)車維修技術(shù)交流考核試卷
- 機(jī)器視覺與圖像處理技術(shù)考核試卷
- 智能儀器儀表項(xiàng)目規(guī)劃考核試卷
- 醫(yī)用針灸貼的種類和使用建議考核試卷
- 供應(yīng)鏈數(shù)字化轉(zhuǎn)型案例與啟示考核試卷
- 木紋設(shè)計(jì)與加工考核試卷
- 苗圃白蟻防治合同范本
- 留置權(quán)合同范本
- 業(yè)擴(kuò)報(bào)裝培訓(xùn)課件
- 8.3 摩擦力(共28張) 2024-2025學(xué)年人教版物理八年級(jí)下冊(cè)
- 中國思想史馬工程課件第一篇 先秦
- HY/T 081-2005紅樹林生態(tài)監(jiān)測(cè)技術(shù)規(guī)程
- Unit 3 Reading and Thinking 課件 【知識(shí)導(dǎo)航+拓展遷移】 高中英語人教版(2019)選擇性必修第二冊(cè)
- 幼兒園中班“建構(gòu)室”活動(dòng)安排表(上學(xué)期和下學(xué)期)
- 農(nóng)村常用法律法規(guī)知識(shí)講座(適用村干部)專題培訓(xùn)課課件
- 部編版四年級(jí)語文下冊(cè)第13課《貓》課件
- 應(yīng)急投入及資源保障制度
- 壓裂評(píng)價(jià)中常見曲線分析
- (新版)網(wǎng)絡(luò)攻防知識(shí)考試題庫(含答案)
- 2023年湖北省技能高考文化綜合試題及答案
- 自然辯證法概論課件:第一章馬克思主義自然觀
評(píng)論
0/150
提交評(píng)論