SpringBoot学习笔记 入门

Spring Boot 学习笔记

SpringBoot 和 Spring 区别:

SpringBoot是一个在Spring的基础上搭建的全新的微框架,其目的是简化Spring的搭建和开发过程。(传统基于Spring的Java Web应用,需要配置web.xml, applicationContext.xml,将应用打成war包放入应用服务器(Tomcat, Jetty等)中并运行。)

特点:

1)、简单易用,初学者和大牛都可以轻松上手,其中注解会给使用者提供方便;
2)、SpringBoot对第三方技术进行了很好的封装和整合,提供了大量的第三方接口;
3)、可以通过依赖自动配置,不需要XML等配置文件
4)、还提供了安全等特性
5)、SpringBoot提供了一堆依赖打包


Gradle(摇篮) 和 Maven 最大的区别,Gradle 抛弃了Maven的xml配置,使其更加简化——个人理解

下面代码片段是 Maven进行依赖配置,可以复制并粘贴到您的构建中。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

下面代码片段是 Gradle进行依赖配置 ,可以复制并粘贴到您的构建中。

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web:1.5.8.RELEASE")
}

SpringBoot 默认使用 tomcat作为服务器 ,使用 logback提供日志记录

前提

SpringBoot提供了一系列的依赖包,所以要使用Maven作为依赖工具。

使用

1、新建一个Maven项目。
2、pom中parent设为spring-boot-starter-parent。建议使用最新的 RELEASE 版本。
否则可能需要设置和。
3、添加应用需要的starter模块,作为示例,我们仅添加web starter模块。
这里需要解释一下starter模块,简单的说,就是一系列的依赖包组合。例如web starter模块,就是包含了SpringBoot预定义的一些Web开发的常用依赖:

  • Spring WebMvc框架
    • spring-web,spring-webmvc
  • 内嵌Tomcat容器
    • tomcat-embed-*
  • 处理JSON数据
    • jackson
  • Spring框架
    • spring-*
  • SpringBoot提供的自动配置功能
    • spring-boot-autoconfigure

换句话说,当你添加了相应的starter模块,就相当于添加了相应的所有必须的依赖包。
starer模块的列表及含义,见:SpringBoot的启动器Starter详解

至此,pom内容如下:

<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.larry.spring</groupId>
    <artifactId>larry-spring-demo4</artifactId>
    <version>0.0.1-SNAPSHOT</version>

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

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

</project>

保存pom,刷新maven,以便刷新依赖导入。

基本上,如果没有特别的需要,现在就可以直接写Controller了!
–特别需要的是指 设置容器、访问端口、路径等。后面做解释。

4、写一个简单的Controller。–直接拿SpringBoot开发新一代SpringJava应用中的示例

package cn.larry.spring.controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@EnableAutoConfiguration
public class SampleController {

    @RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World!";
    }

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

这里有两个新东西:@EnableAutoConfiguration 和 SpringApplication 。

@EnableAtutoConfiguration用于自动配置。简单的说,它会根据你的pom配置(实际上应该是你具体的依赖)来判断这是一个什么应用,并创建相应的环境。

在上面的例子中,@EnableAutoConfiguration会判断出这是一个web应用,所以会创建相应的web环境。

SpringApplication 则是用于从main方法启动Spring应用类。默认,它会执行以下步骤:

  • 1、创建一个合适的ApplicationContext实例(取决于classpath)。
  • 2、注册一个CommandLinePropertySoruce,以便将命令行的参数作为Spring properties。
  • 3、刷新application context,加载所有单例beans。
  • 4、激活所有CommandLineRunner beans。

默认,直接使用SpringApplication 的静态方法run()即可。但也可以创建实例,并自行配置需要的设置。
具体的描述见javadoc即可,如下:

Open Declaration org.springframework.boot.SpringApplication


Classes that can be used to bootstrap and launch a Spring application from a Java main method. By default class will perform the following steps to bootstrap your application: 

Create an appropriate ApplicationContext instance (depending on your classpath) 
Register a CommandLinePropertySource to expose command line arguments as Spring properties 
Refresh the application context, loading all singleton beans 
Trigger any CommandLineRunner beans 
In most circumstances the static run(Object, String []) method can be called directly from your main method to bootstrap your application: 
 @Configuration
 @EnableAutoConfiguration
 public class MyApplication  {

 // ... Bean definitions

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

For more advanced configuration a SpringApplication instance can be created and customized before being run: 

 public static void main(String[] args) throws Exception {
   SpringApplication app = new SpringApplication(MyApplication.class);
   // ... customize app settings here
   app.run(args)
 }

SpringApplications can read beans from a variety of different sources. It is generally recommended that a single @Configuration class is used to bootstrap your application, however, any of the following sources can also be used: 
Class - A Java class to be loaded by AnnotatedBeanDefinitionReader 
Resource - An XML resource to be loaded by XmlBeanDefinitionReader, or a groovy script to be loaded by GroovyBeanDefinitionReader 
Package - A Java package to be scanned by ClassPathBeanDefinitionScanner 
CharSequence - A class name, resource handle or package name to loaded as appropriate. If the CharSequence cannot be resolved to class and does not resolve to a Resource that exists it will be considered a Package. 

直接右键启动main方法即可,也可以用sts(Spring Tools Suite)插件 ,效果一样。

6、默认访问地址:http://localhost:8080
按照之前的Web项目习惯,是有项目路径,但是 SpringBoot默认设置了根路径 。所以直接访问即可,不用添加项目名称。

当然也可设置项目名称,两种方式(application.properties,application.yaml)。
application.properties方式:

## 已经注释,SpringBoot默认用根路径访问(http://localhost:8080)如需填项目名如下:
## Server settings (ServerProperties)
server.port=8080
server.address=127.0.0.1
#server.sessionTimeout=30
server.contextPath=/hsw

## Tomcat specifics
#server.tomcat.accessLogEnabled=false
server.tomcat.protocolHeader=x-forwarded-proto
server.tomcat.remoteIpHeader=x-forwarded-for
server.tomcat.basedir=
server.tomcat.backgroundProcessorDelay=30

application.yaml方式:

## 已经注释,SpringBoot默认用根路径访问(http://localhost:8080)如需填项目名如下:
## .yaml文件默认属性是 以table键 作为子属性,相当于properties里面的点(.),于 python 类似
## Server settings (ServerProperties)
 server:
  port: 8080
  address: 127.0.0.1
  sessionTimeout: 30
  contextPath: /hsw

## Tomcat settings specifics
  tomcat:
    accessLogEnabled: false
    protocolHeader: x-forwarded-proto
    remoteIpHeader: x-forwarded-for
    basedir:
    backgroundProcessorDelay: 30 # secs

之后就需要添加项目名称访问即可。

分析

看一下启动信息如下:

第 9 行,启动SampleController。
第10行,查找active profile,无,设为default。
第11行,刷新上下文。
第12行,初始化tomcat,设置端口8080,设置访问方式为http。
第13行,启动tomcat服务。
第14行,启动Servlet引擎。
第15行,Spring内嵌的WebApplicationContext 初始化开始。
第16行,Spring内嵌的WebApplicationContext 初始化完成。
第17行,映射servlet,将 dispatcherServlet 映射到 [/] 。 
第18行,映射filter,将 characterEncodingFilter 映射到 [/*] 。 
第19行,映射filter,将 hiddenHttpMethodFilter 映射到 [/*] 。 
第20行,映射filter,将 httpPutFormContentFilter 映射到 [/*] 。 
第21行,映射filter,将 requestContextFilter 映射到 [/*] 。 
第22行,查找 @ControllerAdvice。 
第23行,映射路径 "{[/]}" cn.larry.spring.controller.SampleController.home()。 
第24行,映射路径 "{[/error]}" org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)。 
第25行,映射路径 "{[/error],produces=[text/html]}" org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)。 
第26行,略。 第27行,略。 第28行,略。 第29行,略。 
第30行,tomcat启动完毕。 
第31行,SampleController启动耗费的时间。 
第32行,初始化 dispatcherServlet 。 
第33行,dispatcherServlet 的初始化已启动。 
第34行,dispatcherServlet 的初始化已完成。 
第35行,收到shutdown关闭请求。 
第36行,关闭AnnotationConfigEmbeddedWebApplicationContext。 
第37行,略。

从上面的启动信息中可以明显看到SpringMVC的加载过程,特别需要注意的是这种默认方式下加载的几个 filter 。可参考最后三个参考链接

参考

SrpingBoot官网

Spring Boot的启动器Starter详解
Spring Boot——开发新一代Spring Java应用
深入学习微框架:Spring Boot

Spring MVC过滤器-RequestContextFilter
Spring MVC过滤器-HttpPutFormContentFilter
Spring MVC过滤器-HiddenHttpMethodFilter

猜你喜欢

转载自blog.csdn.net/qq_37595946/article/details/78479592
今日推荐