在這一部分,咱們主要了解如下3個問題:css
SpringBoot是Spring項目中的一個子工程,與咱們所熟知的Spring-framework 同屬於spring的產品:html
咱們能夠看到下面的一段介紹:java
Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run".mysql
We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.git
翻譯一下:程序員
Spring Boot你只須要「run」就能夠很是輕易的構建獨立的、生產級別的spring應用。github
咱們爲spring平臺和第三方依賴庫提供了一種固定化的使用方式,使你能很是輕鬆的開始開發你的應用程序。大部分Spring Boot應用只須要不多的配置。web
其實人們把Spring Boot稱爲搭建程序的腳手架
。其最主要做用就是幫咱們快速的構建龐大的spring項目,而且儘量的減小一切xml配置,作到開箱即用,迅速上手,讓咱們關注於業務而非配置。redis
咱們可使用SpringBoot建立java應用,並使用java –jar 啓動它,就能獲得一個生產級別的web工程。spring
java一直被人詬病的一點就是臃腫、麻煩。當咱們還在辛苦的搭建項目時,可能Python程序員已經把功能寫好了,究其緣由主要是兩點:
複雜的配置
項目各類配置實際上是開發時的損耗, 由於在思考 Spring 特性配置和解決業務問題之間須要進行思惟切換,因此寫配置擠佔了寫應用程序邏輯的時間。
混亂的依賴管理
項目的依賴管理也是件吃力不討好的事情。決定項目裏要用哪些庫就已經夠讓人頭痛的了,你還要知道這些庫的哪一個版本和其餘庫不會有衝突,這也是件棘手的問題。而且,依賴管理也是一種損耗,添加依賴不是寫應用程序代碼。一旦選錯了依賴的版本,隨之而來的不兼容問題毫無疑問會是生產力殺手。
而SpringBoot讓這一切成爲過去!
Spring Boot 主要特徵是:
總之,Spring Boot爲全部 Spring 的開發者提供一個開箱即用的、很是快速的、普遍接受的入門體驗
更多細節,你們能夠到官網查看。
接下來,咱們就來利用SpringBoot搭建一個web工程,體會一下SpringBoot的魅力所在!
環境要求:
咱們先新建一個空的demo工程,建立moduel並填寫座標信息。
建立完成後的目錄結構:
看到這裏不少同窗會有疑惑,前面說傳統開發的問題之一就是依賴管理混亂,怎麼這裏咱們還須要管理依賴呢?難道SpringBoot不幫咱們管理嗎?
彆着急,如今咱們的項目與SpringBoot尚未什麼關聯。SpringBoot提供了一個名爲spring-boot-starter-parent的工程,裏面已經對各類經常使用依賴(並不是所有)的版本進行了管理,咱們的項目須要以這個項目爲父工程,這樣咱們就不用操心依賴的版本問題了,須要什麼依賴,直接引入座標便可!
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.itcast.springboot</groupId> <artifactId>itcast-springboot</artifactId> <version>1.0-SNAPSHOT</version> <!-- 全部的springboot的工程都以spring父工程爲父工程 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.6.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>
代碼:
@RestController @EnableAutoConfiguration public class HelloController { @GetMapping("show") public String test(){ return "hello Spring Boot!"; } public static void main(String[] args) { SpringApplication.run(HelloController.class, args); } }
bingo!訪問成功!
入門工程中:pom.xml裏引入了啓動器的概念以@EnableAutoConfiguration註解。
爲了讓SpringBoot幫咱們完成各類自動配置,咱們必須引入SpringBoot提供的自動配置依賴,咱們稱爲啓動器
。spring-boot-starter-parent工程將依賴關係聲明爲一個或者多個啓動器,咱們能夠根據項目需求引入相應的啓動器,由於咱們是web項目,這裏咱們引入web啓動器:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
須要注意的是,咱們並無在這裏指定版本信息。由於SpringBoot的父工程已經對版本進行了管理了。
這個時候,咱們會發現項目中多出了大量的依賴:
這些都是SpringBoot根據spring-boot-starter-web這個依賴自動引入的,並且全部的版本都已經管理好,不會出現衝突。
關於這個註解,官網上有一段說明:
Enable auto-configuration of the Spring Application Context, attempting to guess and configure beans that you are likely to need. Auto-configuration classes are usually applied based on your classpath and what beans you have defined.
簡單翻譯如下:
開啓spring應用程序的自動配置,SpringBoot基於你所添加的依賴和你本身定義的bean,試圖去猜想並配置你想要的配置。好比咱們引入了
spring-boot-starter-web
,而這個啓動器中幫咱們添加了tomcat
、SpringMVC
的依賴。此時自動配置就知道你是要開發一個web應用,因此就幫你完成了web及SpringMVC的默認配置了!
總結,SpringBoot內部對大量的第三方庫或Spring內部庫進行了默認配置,這些配置是否生效,取決於咱們是否引入了對應庫所需的依賴,若是有那麼默認配置就會生效。
因此,咱們使用SpringBoot構建一個項目,只須要引入所需依賴,配置就能夠交給SpringBoot處理了。
如今工程中只有一個Controller,能夠這麼玩;那麼若是有多個Controller,怎麼辦呢?
添加Hello2Controller
代碼:
@RestController public class Hello2Controller { @GetMapping("show2") public String test(){ return "hello Spring Boot2!"; } }
啓動從新啓動,訪問show2測試,失敗:
難道要在每個Controller中都添加一個main方法和@EnableAutoConfiguration註解,這樣啓動一個springboot程序也太麻煩了。也沒法同時啓動多個Controller,由於每一個main方法都監聽8080端口。因此,一個springboot程序應該只有一個springboot的main方法。
因此,springboot程序引入了一個全局的引導類。
一般請求下,咱們在一個springboot工程中都會在基包下建立一個引導類,一些springboot的全局註解(@EnableAutoConfiguration註解)以及springboot程序的入口main方法都放在該類中。
在springboot的程序的基包下(引導類和Controller包在同級目錄下),建立TestApplication.class:
內容以下:
@EnableAutoConfiguration public class TestApplication { public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); } }
並修改HelloController,去掉main方法及@EnableAutoConfiguration:
@RestController public class HelloController { @GetMapping("show") public String test(){ return "hello Spring Boot!"; } }
啓動引導類,訪問show測試:
發現全部的Controller都不能訪問,爲何?
回想之前程序,咱們在配置文件中添加了註解掃描,它能掃描指定包下的全部Controller,而如今並無。怎麼解決——@ComponentScan註解
spring框架除了提供配置方式的註解掃描<context:component-scan />
,還提供了註解方式的註解掃描@ComponentScan
。
在TestApplication.class中,使用@ComponentScan註解:
@EnableAutoConfiguration @ComponentScan public class TestApplication { public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); } }
從新啓動,訪問show或者show2:
咱們跟進該註解的源碼,並無看到什麼特殊的地方。咱們查看註釋:
大概的意思:
配置組件掃描的指令。提供了相似與
<context:component-scan>
標籤的做用經過basePackageClasses或者basePackages屬性來指定要掃描的包。若是沒有指定這些屬性,那麼將從聲明這個註解的類所在的包開始,掃描包及子包
而咱們的@ComponentScan註解聲明的類就是main函數所在的啓動類,所以掃描的包是該類所在包及其子包。通常啓動類會放在一個比較淺的包目錄中。
咱們如今的引導類中使用了@EnableAutoConfiguration和@ComponentScan註解,有點麻煩。springboot提供了一種簡便的玩法:@SpringBootApplication註解
使用@SpringBootApplication改造TestApplication:
@SpringBootApplication public class TestApplication { public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); } }
點擊進入,查看源碼:
發現@SpringBootApplication實際上是一個組合註解,這裏重點的註解有3個:
@SpringBootConfiguration註解的源碼:
咱們繼續點擊查看源碼:
經過這段咱們能夠看出,在這個註解上面,又有一個@Configuration
註解。經過上面的註釋閱讀咱們知道:這個註解的做用就是聲明當前類是一個配置類,而後Spring會自動掃描到添加了@Configuration
的類,而且讀取其中的配置信息。而@SpringBootConfiguration
是來聲明當前類是SpringBoot應用的配置類,項目中只能有一個。因此通常咱們無需本身添加。
springboot的默認配置方式和咱們以前玩的配置方式不太同樣,沒有任何的xml。那麼若是本身要新增配置該怎麼辦?好比咱們要配置一個數據庫鏈接池,之前會這麼作:
<!-- 配置鏈接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean>
如今該怎麼作呢?
事實上,在Spring3.0開始,Spring官方就已經開始推薦使用java配置來代替傳統的xml配置了,咱們不妨來回顧一下Spring的歷史:
Spring1.0時代
在此時由於jdk1.5剛剛出來,註解開發並未盛行,所以一切Spring配置都是xml格式,想象一下全部的bean都用xml配置,細思極恐啊,心疼那個時候的程序員2秒
Spring2.0時代
Spring引入了註解開發,可是由於並不完善,所以並未徹底替代xml,此時的程序員每每是把xml與註解進行結合,貌似咱們以前都是這種方式。
Spring3.0及之後
3.0之後Spring的註解已經很是完善了,所以Spring推薦你們使用徹底的java配置來代替之前的xml,不過彷佛在國內並未推廣盛行。而後當SpringBoot來臨,人們才慢慢認識到java配置的優雅。
有句古話說的好:擁抱變化,擁抱將來。因此咱們也應該順應時代潮流,作時尚的弄潮兒,一塊兒來學習下java配置的玩法。
java配置主要靠java類和一些註解來達到和xml配置同樣的效果,比較經常使用的註解有:
@Configuration
:聲明一個類做爲配置類,代替xml文件@Bean
:聲明在方法上,將方法的返回值加入Bean容器,代替<bean>
標籤@Value
:屬性注入@PropertySource
:指定外部屬性文件。咱們接下來用java配置來嘗試實現鏈接池配置
首先在pom.xml中,引入Druid鏈接池依賴:
<dependency> <groupId>com.github.drtrang</groupId> <artifactId>druid-spring-boot2-starter</artifactId> <version>1.1.10</version> </dependency>
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/leyou jdbc.username=root jdbc.password=root
建立JdbcConfiguration類:
@Configuration @PropertySource("classpath:jdbc.properties") public class JdbcConfiguration { @Value("${jdbc.url}") String url; @Value("${jdbc.driverClassName}") String driverClassName; @Value("${jdbc.username}") String username; @Value("${jdbc.password}") String password; @Bean public DataSource dataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(url); dataSource.setDriverClassName(driverClassName); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } }
解讀:
@Configuration
:聲明JdbcConfiguration
是一個配置類。@PropertySource
:指定屬性文件的路徑是:classpath:jdbc.properties
@Value
爲屬性注入值。dataSource()
方法聲明爲一個註冊Bean的方法,Spring會自動調用該方法,將方法的返回值加入Spring容器中。至關於之前的bean標籤而後就能夠在任意位置經過@Autowired
注入DataSource了!
咱們在HelloController
中測試:
@RestController public class HelloController { @Autowired private DataSource dataSource; @GetMapping("show") public String test(){ return "hello Spring Boot!"; } }
在test方法中打一個斷點,而後Debug運行並查看:
屬性注入成功了!
在上面的案例中,咱們實驗了java配置方式。不過屬性注入使用的是@Value註解。這種方式雖然可行,可是不夠強大,由於它只能注入基本類型值。
在SpringBoot中,提供了一種新的屬性注入方式,支持各類java基本數據類型及複雜類型的注入。
1)新建JdbcProperties
,用來進行屬性注入:
代碼:
@ConfigurationProperties(prefix = "jdbc") public class JdbcProperties { private String url; private String driverClassName; private String username; private String password; // ... 略 // getters 和 setters }
在類上經過@ConfigurationProperties註解聲明當前類爲屬性讀取類
prefix="jdbc"
讀取屬性文件中,前綴爲jdbc的值。
在類上定義各個屬性,名稱必須與屬性文件中jdbc.
後面部分一致,而且必須具備getter和setter方法
須要注意的是,這裏咱們並無指定屬性文件的地址,SpringBoot默認會讀取文件名爲application.properties的資源文件,因此咱們把jdbc.properties名稱改成application.properties
2)在JdbcConfiguration中使用這個屬性:
經過@EnableConfigurationProperties(JdbcProperties.class)
來聲明要使用JdbcProperties
這個類的對象
而後你能夠經過如下方式在JdbcConfiguration類中注入JdbcProperties:
@Configuration @EnableConfigurationProperties(JdbcProperties.class) public class JdbcConfiguration { @Autowired private JdbcProperties jdbcProperties; @Bean public DataSource dataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(jdbcProperties.getUrl()); dataSource.setDriverClassName(jdbcProperties.getDriverClassName()); dataSource.setUsername(jdbcProperties.getUsername()); dataSource.setPassword(jdbcProperties.getPassword()); return dataSource; } }
@Configuration @EnableConfigurationProperties(JdbcProperties.class) public class JdbcConfiguration { private JdbcProperties jdbcProperties; public JdbcConfiguration(JdbcProperties jdbcProperties){ this.jdbcProperties = jdbcProperties; } @Bean public DataSource dataSource() { // 略 } }
@Configuration @EnableConfigurationProperties(JdbcProperties.class) public class JdbcConfiguration { @Bean public DataSource dataSource(JdbcProperties jdbcProperties) { // ... } }
本例中,咱們採用第三種方式。
3)測試結果:
你們會以爲這種方式彷佛更麻煩了,事實上這種方式有更強大的功能,也是SpringBoot推薦的注入方式。二者對比關係:
優點:
Relaxed binding:鬆散綁定
事實上,若是一段屬性只有一個Bean須要使用,咱們無需將其注入到一個類(JdbcProperties)中。而是直接在須要的地方聲明便可:
@Configuration public class JdbcConfiguration { @Bean // 聲明要注入的屬性前綴,SpringBoot會自動把相關屬性經過set方法注入到DataSource中 @ConfigurationProperties(prefix = "jdbc") public DataSource dataSource() { DruidDataSource dataSource = new DruidDataSource(); return dataSource; } }
咱們直接把@ConfigurationProperties(prefix = "jdbc")
聲明在須要使用的@Bean
的方法上,而後SpringBoot就會自動調用這個Bean(此處是DataSource)的set方法,而後完成注入。使用的前提是:該類必須有對應屬性的set方法!
咱們將jdbc的url改爲:/heima,再次測試:
經過剛纔的學習,咱們知道@EnableAutoConfiguration會開啓SpringBoot的自動配置,而且根據你引入的依賴來生效對應的默認配置。那麼問題來了:
其實在咱們的項目中,已經引入了一個依賴:spring-boot-autoconfigure,其中定義了大量自動配置類:
還有:
很是多,幾乎涵蓋了如今主流的開源框架,例如:
... 等等
咱們來看一個咱們熟悉的,例如SpringMVC,查看mvc 的自動配置類:
打開WebMvcAutoConfiguration:
咱們看到這個類上的4個註解:
@Configuration
:聲明這個類是一個配置類
@ConditionalOnWebApplication(type = Type.SERVLET)
ConditionalOn,翻譯就是在某個條件下,此處就是知足項目的類是是Type.SERVLET類型,也就是一個普通web工程,顯然咱們就是
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
這裏的條件是OnClass,也就是知足如下類存在:Servlet、DispatcherServlet、WebMvcConfigurer,其中Servlet只要引入了tomcat依賴天然會有,後兩個須要引入SpringMVC纔會有。這裏就是判斷你是否引入了相關依賴,引入依賴後該條件成立,當前類的配置纔會生效!
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
這個條件與上面不一樣,OnMissingBean,是說環境中沒有指定的Bean這個才生效。其實這就是自定義配置的入口,也就是說,若是咱們本身配置了一個WebMVCConfigurationSupport的類,那麼這個默認配置就會失效!
接着,咱們查看該類中定義了什麼:
視圖解析器:
處理器適配器(HandlerAdapter):
還有不少,這裏就不一一截圖了。
另外,這些默認配置的屬性來自哪裏呢?
咱們看到,這裏經過@EnableAutoConfiguration註解引入了兩個屬性:WebMvcProperties和ResourceProperties。
咱們查看這兩個屬性類:
找到了內部資源視圖解析器的prefix和suffix屬性。
ResourceProperties中主要定義了靜態資源(.js,.html,.css等)的路徑:
若是咱們要覆蓋這些默認屬性,只須要在application.properties中定義與其前綴prefix和字段名一致的屬性便可。
SpringBoot爲咱們提供了默認配置,而默認配置生效的條件通常有兩個:
1)啓動器
之因此,咱們若是不想配置,只須要引入依賴便可,而依賴版本咱們也不用操心,由於只要引入了SpringBoot提供的stater(啓動器),就會自動管理依賴及版本了。
所以,玩SpringBoot的第一件事情,就是找啓動器,SpringBoot提供了大量的默認啓動器,參考SpringBoot啓動器
2)全局配置
另外,SpringBoot的默認配置,都會讀取默認屬性,而這些屬性能夠經過自定義application.properties
文件來進行覆蓋。這樣雖然使用的仍是默認配置,可是配置中的值改爲了咱們自定義的。
所以,玩SpringBoot的第二件事情,就是經過application.properties
來覆蓋默認屬性值,造成自定義配置。咱們須要知道SpringBoot的默認屬性key,很是多,參考SpringBoot全局屬性
接下來,咱們來看看如何用SpringBoot來玩轉之前的SSM,咱們使用數據庫tb_user和實體類User
pom.xml:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.itcast.user</groupId> <artifactId>itcast-user</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.6.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>
參照上邊的項目,編寫引導類:
@SpringBootApplication public class UserApplication { public static void main(String[] args) { SpringApplication.run(UserApplication.class); } }
編寫UserController:
@RestController @RequestMapping("user") public class UserController { @GetMapping("hello") public String test(){ return "hello ssm"; } }
雖然默認配置已經可使用SpringMVC了,不過咱們有時候須要進行自定義配置。
添加全局配置文件:application.properties
端口經過如下方式配置
# 映射端口 server.port=80
重啓服務後測試:
如今,咱們的項目是一個jar工程,那麼就沒有webapp,咱們的靜態資源該放哪裏呢?
回顧咱們上面看的源碼,有一個叫作ResourceProperties的類,裏面就定義了靜態資源的默認查找路徑:
默認的靜態資源路徑爲:
只要靜態資源放在這些目錄中任何一個,SpringMVC都會幫咱們處理。
咱們習慣會把靜態資源放在classpath:/static/
目錄下。咱們建立目錄,而且添加一些靜態資源:
重啓項目後測試:
攔截器也是咱們常常須要使用的,在SpringBoot中該如何配置呢?
攔截器不是一個普通屬性,而是一個類,因此就要用到java配置方式了。在SpringBoot官方文檔中有這麼一段說明:
If you want to keep Spring Boot MVC features and you want to add additional MVC configuration (interceptors, formatters, view controllers, and other features), you can add your own
@Configuration
class of typeWebMvcConfigurer
but without@EnableWebMvc
. If you wish to provide custom instances ofRequestMappingHandlerMapping
,RequestMappingHandlerAdapter
, orExceptionHandlerExceptionResolver
, you can declare aWebMvcRegistrationsAdapter
instance to provide such components.If you want to take complete control of Spring MVC, you can add your own
@Configuration
annotated with@EnableWebMvc
.
翻譯:
若是你想要保持Spring Boot 的一些默認MVC特徵,同時又想自定義一些MVC配置(包括:攔截器,格式化器, 視圖控制器、消息轉換器 等等),你應該讓一個類實現
WebMvcConfigurer
,而且添加@Configuration
註解,可是千萬不要加@EnableWebMvc
註解。若是你想要自定義HandlerMapping
、HandlerAdapter
、ExceptionResolver
等組件,你能夠建立一個WebMvcRegistrationsAdapter
實例 來提供以上組件。若是你想要徹底自定義SpringMVC,不保留SpringBoot提供的一切特徵,你能夠本身定義類而且添加
@Configuration
註解和@EnableWebMvc
註解
總結:經過實現WebMvcConfigurer
並添加@Configuration
註解來實現自定義部分SpringMvc配置。
實現以下:
首先咱們定義一個攔截器:
@Component public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandle method is running!"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle method is running!"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion method is running!"); } }
而後定義配置類,註冊攔截器:
@Configuration public class MvcConfiguration implements WebMvcConfigurer { @Autowired private HandlerInterceptor myInterceptor; /** * 重寫接口中的addInterceptors方法,添加自定義攔截器 * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor).addPathPatterns("/**"); } }
接下來運行並查看日誌:
preHandle method is running! postHandle method is running! afterCompletion method is running!
你會發現日誌中只有這些打印信息,springMVC的日誌信息都沒有,由於springMVC記錄的log級別是debug,springboot默認是顯示info以上,咱們須要進行配置。
SpringBoot經過logging.level.*=debug
來配置日誌級別,*填寫包名
# 設置org.springframework包的日誌級別爲debug logging.level.org.springframework=debug
再次運行查看:
jdbc鏈接池是spring配置中的重要一環,在SpringBoot中該如何處理呢?
答案是不須要處理,咱們只要找到SpringBoot提供的啓動器便可:
在pom.xml中引入jdbc的啓動器:
<!--jdbc的啓動器,默認使用HikariCP鏈接池--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--不要忘記數據庫驅動,由於springboot不知道咱們使用的什麼數據庫,這裏選擇mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
SpringBoot已經自動幫咱們引入了一個鏈接池:
HikariCP應該是目前速度最快的鏈接池了,咱們看看它與c3p0的對比:
所以,咱們只須要指定鏈接池參數便可:
# 鏈接四大參數 spring.datasource.url=jdbc:mysql://localhost:3306/heima spring.datasource.username=root spring.datasource.password=root # 可省略,SpringBoot自動推斷 spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.hikari.idle-timeout=60000 spring.datasource.hikari.maximum-pool-size=30 spring.datasource.hikari.minimum-idle=10
固然,若是你更喜歡Druid鏈接池,也可使用Druid官方提供的啓動器:
<!-- Druid鏈接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.6</version> </dependency>
而鏈接信息的配置與上面是相似的,只不過在鏈接池特有屬性上,方式略有不一樣:
#初始化鏈接數 spring.datasource.druid.initial-size=1 #最小空閒鏈接 spring.datasource.druid.min-idle=1 #最大活動鏈接 spring.datasource.druid.max-active=20 #獲取鏈接時測試是否可用 spring.datasource.druid.test-on-borrow=true #監控頁面啓動 spring.datasource.druid.stat-view-servlet.allow=true
SpringBoot官方並無提供Mybatis的啓動器,不過Mybatis官方本身實現了:
<!--mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency>
配置,基本沒有須要配置的:
# mybatis 別名掃描 mybatis.type-aliases-package=cn.itcast.pojo # mapper.xml文件位置,若是沒有映射文件,請註釋掉 mybatis.mapper-locations=classpath:mappers/*.xml
須要注意,這裏沒有配置mapper接口掃描包,所以咱們須要給每個Mapper接口添加@Mapper
註解,才能被識別。
@Mapper public interface UserMapper { }
user對象:
@Table(name = "tb_user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String userName; private String password; private String name; private Integer age; private Integer sex; private Date birthday; private Date created; private Date updated; //getter and setter 省略... }
接下來,就去集成通用mapper。
通用Mapper的做者也爲本身的插件編寫了啓動器,咱們直接引入便可:
<!-- 通用mapper --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.0.2</version> </dependency>
不須要作任何配置就可使用了。
@Mapper public interface UserMapper extends tk.mybatis.mapper.common.Mapper<User>{ }
其實,咱們引入jdbc或者web的啓動器,就已經引入事務相關的依賴及默認配置了
至於事務,SpringBoot中經過註解來控制。就是咱們熟知的@Transactional
@Service public class UserService { @Autowired private UserMapper userMapper; public User queryById(Long id){ return this.userMapper.selectByPrimaryKey(id); } @Transactional public void deleteById(Long id){ this.userMapper.deleteByPrimaryKey(id); } }
在UserController中添加測試方法,內容:
@RestController @RequestMapping("user") public class UserController { @Autowired private UserService userService; @GetMapping("{id}") public User queryUserById(@PathVariable("id")Long id){ return this.userService.queryById(id); } @GetMapping("hello") public String test(){ return "hello ssm"; } }
咱們啓動項目,查看:
完整的pom.xml:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.itcast.user</groupId> <artifactId>itcast-user</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.6.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--jdbc的啓動器,默認使用HikariCP鏈接池--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--不要忘記數據庫驅動,由於springboot不知道咱們使用的什麼數據庫,這裏選擇mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!--mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <!-- 通用mapper --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.0.2</version> </dependency> </dependencies> </project>
完整的application.properties:
server.port=80 logging.level.org.springframework=debug spring.datasource.url=jdbc:mysql://localhost:3306/heima spring.datasource.username=root spring.datasource.password=root # mybatis 別名掃描 mybatis.type-aliases-package=cn.itcast.pojo # mapper.xml文件位置,若是沒有映射文件,請註釋掉 # mybatis.mapper-locations=classpath:mappers/*.xml
SpringBoot並不推薦使用jsp,可是支持一些模板引擎技術:
之前你們用的比較多的是Freemarker,可是咱們今天的主角是Thymeleaf!
簡單說, Thymeleaf 是一個跟 Velocity、FreeMarker 相似的模板引擎,它能夠徹底替代 JSP 。相較於其餘的模板引擎,它有以下四個極吸引人的特色:
接下來,咱們就經過入門案例來體會Thymeleaf的魅力:
編寫一個controller方法,返回一些用戶數據,放入模型中,未來在頁面渲染
@GetMapping("/all") public String all(ModelMap model) { // 查詢用戶 List<User> users = this.userService.queryAll(); // 放入模型 model.addAttribute("users", users); // 返回模板名稱(就是classpath:/templates/目錄下的html文件名) return "users"; }
直接引入啓動器:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
SpringBoot會自動爲Thymeleaf註冊一個視圖解析器:
與解析JSP的InternalViewResolver相似,Thymeleaf也會根據前綴和後綴來肯定模板文件的位置:
classpath:/templates/
.html
因此若是咱們返回視圖:users
,會指向到 classpath:/templates/users.html
通常咱們無需進行修改,默認便可。
根據上面的文檔介紹,模板默認放在classpath下的templates文件夾,咱們新建一個html文件放入其中:
編寫html模板,渲染模型中的數據:
注意,把html 的名稱空間,改爲:xmlns:th="http://www.thymeleaf.org"
會有語法提示
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>首頁</title> <style type="text/css"> table {border-collapse: collapse; font-size: 14px; width: 80%; margin: auto} table, th, td {border: 1px solid darkslategray;padding: 10px} </style> </head> <body> <div style="text-align: center"> <span style="color: darkslategray; font-size: 30px">歡迎光臨!</span> <hr/> <table class="list"> <tr> <th>id</th> <th>姓名</th> <th>用戶名</th> <th>年齡</th> <th>性別</th> <th>生日</th> </tr> <tr th:each="user : ${users}"> <td th:text="${user.id}">1</td> <td th:text="${user.name}">張三</td> <td th:text="${user.userName}">zhangsan</td> <td th:text="${user.age}">20</td> <td th:text="${user.sex}">男</td> <td th:text="${user.birthday}">1980-02-30</td> </tr> </table> </div> </body> </html>
咱們看到這裏使用瞭如下語法:
${}
:這個相似與el表達式,但實際上是ognl的語法,比el表達式更增強大th-
指令:th-
是利用了Html5中的自定義屬性來實現的。若是不支持H5,能夠用data-th-
來代替
th:each
:相似於c:foreach
遍歷集合,可是語法更加簡潔th:text
:聲明標籤中的文本
<td th-text='${user.id}'>1</td>
,若是user.id有值,會覆蓋默認的1接下來,咱們打開頁面測試一下:
Thymeleaf會在第一次對模板解析以後進行緩存,極大的提升了併發處理能力。可是這給咱們開發帶來了不便,修改頁面後並不會馬上看到效果,咱們開發階段能夠關掉緩存使用:
# 開發階段關閉thymeleaf的模板緩存 spring.thymeleaf.cache=false
注意:
在Idea中,咱們須要在修改頁面後按快捷鍵:`Ctrl + Shift + F9` 對項目進行rebuild才能夠。 eclipse中沒有測試過。
咱們能夠修改頁面,測試一下。