Springboot入門教程

weixin_33850890發表於2018-08-08

一、 Springboot簡介
Spring Boot是為了簡化Spring應用的建立、執行、除錯、部署等而出現的,使用它可以做到專注於Spring應用的開發,而無需過多關注XML的配置。 簡單來說,它提供了一堆依賴打包,並已經按照使用習慣解決了依賴問題---習慣大於約定。 Spring Boot預設使用tomcat作為伺服器,使用logback提供日誌記錄。 Spring Boot提供了一系列的依賴包,所以需要構建工具的支援:maven 或 gradle。
二、 Springboot啟動器
spring-boot-starter
這是Spring Boot的核心啟動器,包含了自動配置、日誌和YAML。 2)spring-boot-starter-actuator
幫助監控和管理應用。 3)spring-boot-starter-amqp
通過spring-rabbit來支援AMQP協議(Advanced Message Queuing Protocol)。 4)spring-boot-starter-aop
支援面向方面的程式設計即AOP,包括spring-aop和AspectJ。 5)spring-boot-starter-artemis
通過Apache Artemis支援JMS的API(Java Message Service API)。 6)spring-boot-starter-batch
支援Spring Batch,包括HSQLDB資料庫。 7)spring-boot-starter-cache
支援Spring的Cache抽象。 8)spring-boot-starter-cloud-connectors
支援Spring Cloud Connectors,簡化了在像Cloud Foundry或Heroku這樣的雲平臺上連線服務。 9)spring-boot-starter-data-elasticsearch
支援ElasticSearch搜尋和分析引擎,包括spring-data-elasticsearch。 10)spring-boot-starter-data-gemfire
支援GemFire分散式資料儲存,包括spring-data-gemfire。 11)spring-boot-starter-data-jpa
支援JPA(java Persistence API),包括spring-data-jpa、spring-orm、hibernate。 12)spring-boot-starter-data-MongoDB
支援mongodb資料,包括spring-data-mongodb。 13)spring-boot-starter-data-rest
通過spring-data-rest-webmvc,支援通過REST暴露Spring Data資料倉儲。 14)spring-boot-starter-data-solr
支援Apache Solr搜尋平臺,包括spring-data-solr。 15)spring-boot-starter-freemarker
支援FreeMarker模板引擎。 16)spring-boot-starter-groovy-templates
支援Groovy模板引擎。 17)spring-boot-starter-hateoas
通過spring-hateoas支援基於HATEOAS的RESTful Web服務。 18)spring-boot-starter-hornetq
通過HornetQ支援JMS。 19)spring-boot-starter-integration
支援通用的spring-integration模組。 20)spring-boot-starter-jdbc
支援JDBC資料庫。 21)spring-boot-starter-jersey
支援Jersey RESTful Web服務框架。 22)spring-boot-starter-jta-atomikos
通過Atomikos支援JTA分散式事務處理。 23)spring-boot-starter-jta-bitronix
通過Bitronix支援JTA分散式事務處理。 24)spring-boot-starter-mail
支援javax.mail模組。 25)spring-boot-starter-mobile
支援spring-mobile。 26)spring-boot-starter-mustache
支援Mustache模板引擎。 27)spring-boot-starter-Redis
支援redis鍵值儲存資料庫,包括spring-redis。 28)spring-boot-starter-security
支援spring-security。 29)spring-boot-starter-social-facebook
支援spring-social-facebook 30)spring-boot-starter-social-linkedin
支援pring-social-linkedin 31)spring-boot-starter-social-twitter
支援pring-social-twitter 32)spring-boot-starter-test
支援常規的測試依賴,包括JUnit、Hamcrest、Mockito以及spring-test模組。 33)spring-boot-starter-thymeleaf
支援Thymeleaf模板引擎,包括與Spring的整合。 34)spring-boot-starter-velocity
支援Velocity模板引擎。 35)spring-boot-starter-web
S支援全棧式Web開發,包括Tomcat和spring-webmvc。 36)spring-boot-starter-websocket
支援WebSocket開發。 37)spring-boot-starter-ws
支援Spring Web Services。
三、 一個簡單的Springboot示例
Pom.xml配置
Springboot父工程依賴,會引入一些SpringBoot相關的一些依賴和配置,使用SpringBoot必須有這個parent

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.6.RELEASE</version>
    <relativePath/>
</parent>

Springboot web啟動器依賴(有了該依賴就可以使用SpringMvc相關的功能了)

<dependency>
    <groupId>org.springframework.boot</groupId>         
        <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

之後寫一個啟動類即可完成Springboot專案的搭建

/**
 * @SpringBootApplication 相當於 @Configuration,@EnableAutoConfiguration對Configuration註解的掃描,@ComponentScan包掃描 這個註解必須要
*/
@SpringBootApplication(scanBasePackages = {"com.yubin"})
public class SpringBootStart {
       public static void main(String[] args) {
                SpringApplication.run(SpringBootStart.class, args);
       }
}

四、SpringBoot如何實現SpringMvc
1、框架搭建及必要依賴的引入 使用之前的案例
2、新建一個啟動類

/**
 * SpringBoot演示用例啟動器類
 *
 * @Author YUBIN
 */
/**
 * @SpringBootApplication 包含了@Configuration,@EnableAutoConfiguration和@ComponentScan
 * @Configuration 相當於Spring的xml配置檔案;使用java程式碼可以檢查型別安全
 * @EnableAutoConfiguration 自動配置
 * @ComponentScan 元件掃描,可自動發現和裝配一些Bean
 */
@SpringBootApplication(scanBasePackages = {"com.yubin.springboot"}) // scanBasePackages 屬性配置包掃描
@MapperScan(basePackages = "com.yubin.springboot.dao")
@ServletComponentScan // 該註解使得Servlet、Filter、Listener 可以直接通過 @WebServlet、@WebFilter、@WebListener 註解自動註冊,無需其他程式碼
public class SpringBootDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemoApplication.class, args);
    }
} 

3、新建一個IndexController類

@Controller
public class IndexController {

   @RequestMapping(value = {"/index","/show"},method = RequestMethod.GET) // 訪問連結可以是index,也可以是show method屬性現在請求方式
   @ResponseBody // 響應json格式的資料
   public Map<String, String> index() {
       Map<String, String> map = new HashMap<>();
       map.put("俞斌", "是帥哥GET");
       map.put("你好", "SpringBoot好方便");
       return map;
   }
}

4、執行啟動類測試
專案通過main方法啟動之後,就可以進行訪問了 http://localhost:8080/index
預設什麼配置都沒有的話,根路徑為"/",埠號是 8080

12741791-e0404977107b753f.png
image.png

至此:SpringBoot下使用SpringMvc的簡單案例就完成了

5、優化
(1)、在類上面使用@RestController就不需要再每個方法上都寫上@ResponseBody註解了
這個註解是Spring4.0之後出來的 包含了@Controller和@ResponseBody兩個註解


12741791-711343fcb951f187.png
image.png

(2)、方法上對映方式的註解@RequestMappint
一般我們在使用@RequestMapping的時候會限制該方法的請求方式GET或者POST,每次都需要在RequestMapping中書寫method屬性,會顯得很麻煩,有沒有好一點的辦法呢?答案是肯定的
GET請求可以使用 @GetMapping


12741791-2ed83b7086de6527.png
image.png

POST請求可以使用 @PostMapping


12741791-c3e1b3dce4bd4ec8.png
image.png

上面的這些註解是Spring4.3之後出來的
演示:

12741791-f76316c7536f8b74.png
image.png

六、 專案埠號設定
在0配置的情況下,專案的埠號預設是8080,可以在ServerProperties這個類中進行檢視
12741791-7ac276580bdad473.png
image.png

12741791-d6861378d2c162ee.png
image.png

進入ConfigurableEmbeddedServletContainer類
12741791-085a84aca4123858.png
image.png

12741791-e7350b315e6fb09b.png
image.png

那麼如何更改專案的埠號呢
在resources目錄下新建一個application.properties檔案或者application.yml檔案
注意:這兩個檔案application.properties的優先順序更高
12741791-89b8785f146c3dbd.png
image.png

重新啟動專案,埠號就會發生變化
七、 springboot啟動預設圖示
使用banner線上生成工具
http://www.bootschool.net/ascii;jsessionid=B94EBFF1EA05958A7AE2C0F9B9300D9C
預設是在resourcers目錄下新建banner.txt檔案,如果需要更改檔名可以在application.properties中書寫
八、 Springboot Servlet註冊
SpringBoot中有兩種方式可以新增Servlet、Filter、Listener
1、程式碼註冊通過ServletRegistrationBean、FilterRegistrationBean和ServletListenerRegistrationBean獲得控制(在啟動器中書寫的)

@Bean // @Bean與@Configuration的區別是 @Bean必須有返回值 與spring配置檔案中的bean標籤同
public ServletRegistrationBean servletRegistrationBean() {
    return new ServletRegistrationBean(new Hello1Servlet(), "/helloServlet/*");
}

2、在 SpringBoot啟動器 上使用@ServletComponentScan 註解後,Servlet、Filter、Listener 可以直接通過 @WebServlet、@WebFilter、@WebListener 註解自動註冊,無需其他程式碼
具體的實現方式參照專案的 servlet、filter、listener包下的程式碼以及SpringBoot的啟動器
Springboot如何配置在專案啟動的時候就對servlet進行初始化呢?
像filter和servlet的一些屬性可以通過註解的屬性來設定
九、 SpringBoot攔截器
1、SpringBoot攔截器的定義步驟
(1)、建立我們自己的攔截器類並實現HandlerInterceptor介面


12741791-365ea6bd1deb1a36.png
image.png

12741791-de095dec6330f727.png
image.png

(2)、建立一個Java類繼承WebMvcConfigurerAdapter,並重寫addInterceptors方法。


12741791-22012f90b90cd058.png
image.png

12741791-b713487e7ce63e76.png
image.png

(3)例項化我們自定義的攔截器,然後將物件手動新增到攔截器鏈中(在addInterceptors方法中新增)。
12741791-7f36e466ead57471.png
image.png

2、SpringBoot攔截器的個人總結
(1)、當我訪問自定義的Servlet的時候會被Spring的攔截器給攔截麼?
不會。因為Servlet沒有被Spring所管理
十、 SpringBoot MyBatis
1、pom.xml 配置maven依賴
    <!-- springboot和mybatis整合包 -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.1.1</version>
    </dependency>

    <!-- mysql 資料庫驅動包 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

2、在配置檔案application.properties中加上配置

# 資料庫連線池
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/ssm
spring.datasource.username=root
spring.datasource.password=root123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#如果不使用註解的話可以在配置檔案中配置mapper對映檔案路徑和型別別名
#mybatis配置
#型別別名
mybatis.type-aliases-package=com.yubin.springboot.pojo
#指定mapper.xml的位置
mybatis.mapper-locations=classpath:mybatis/*.xml

#mybatis.typeAliasesPackage=com.yubin.bean
#mybatis.mapperLocations=classpath:com/yubin/mapper/*.xml

3、使用方式與SSM中的Mybatis基本相同
需要注意的是:
(1)、如何讓容器掃描到Mapper介面呢?
方式一、在SpringBoot的啟動器上面加上@MapperScan("com.yubin.dao")
方式二、在Mapper介面上加上@Repository註解(這個用於Mybatis的時候不行)
兩者的區別是:方式一會代理指定包下的所有介面,方式二隻會代理加了註解的介面

4、書寫測試類

<!-- test 啟動器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
// SpringJUnit支援,由此引入Spring-Test框架支援!
@RunWith(SpringRunner.class)
// 指定我們SpringBoot工程的Application啟動類
@SpringBootTest(classes = SpringBootStart.class)
// 由於是Web專案,Junit需要模擬ServletContext,因此我們需要給我們的測試類加上@WebAppConfiguration。
@WebAppConfiguration
public class MyTest {

    @Autowired
    private CommonMapper commonMapper;

    @Test
    public void test1() {
        //PageHelper.startPage(1, 1);
        System.out.println(commonMapper.queryContent(new HashMap()));
    }
}