Spring Boot·入门

CY 2019年03月02日 1,080次浏览

1、Spring Boot 简介

简化Spring应用开发的一个框架;免去Spring的配置文件

整个Spring技术栈的一个大整合;

J2EE开发的一站式解决方案;

2、微服务

2014,martin fowler

微服务:架构风格(服务微化)

一个应用应该是一组小型服务;可以通过HTTP的方式进行互通;

单体应用:ALL IN ONE

微服务:每一个功能元素最终都是一个可独立替换和独立升级的软件单元;

详细参照微服务文档

3、环境准备

  • jdk1.8:Spring Boot 推荐jdk1.8及以上;我使用的Java版本java version "1.8.0_221"
  • maven3.x:maven 3.3以上版本;Apache Maven 3.6.1
  • IntelliJIDEA2019:IntelliJ IDEA 2019.2 x64、STS
  • SpringBoot 2.1.8.RELEASE:2.1.8;

3.1、MAVEN设置;

mavensettings.xml配置文件的profiles标签添加,使得mvn默认使用1.8版本的java进行编译

<profile>
  <id>jdk-1.8</id>
  <activation>
    <activeByDefault>true</activeByDefault>
    <jdk>1.8</jdk>
  </activation>
  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
  </properties>
</profile>

3.2、IDEA设置

配置maven:我使用的IDEA默认自带的Maven,他的仓库和配置文件都在用户目录下的.m2文件夹中

配置maven的settings.xml配置默认使用Aliyun仓库:

<mirror>
    <id>Aliyun</id>
    <mirrorOf>central</mirrorOf>
    <name>The Mirror Of Aliyun.</name>
    <url>https://maven.aliyun.com/repository/public</url>
</mirror>

4、Spring Boot HelloWorld

实现一个功能:

浏览器发送hello请求,服务器接受请求并处理,响应Hello World字符串;

4.1、使用IDEA创建一个maven工程;(jar)

4.2、导入spring boot相关的依赖

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.example</groupId>
	<artifactId>myproject</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<!-- Inherit defaults from Spring Boot -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.8.RELEASE</version>
	</parent>

	<!-- Add typical dependencies for a web application -->
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>

	<!-- Package as an executable jar -->
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

参考文档:Maven Installation

4.3、编写一个主程序;启动Spring Boot应用

package com.example.spring_boot_demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootDemoApplication {

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

}

4.4、编写相关的Controller

参考文档

package com.example.spring_boot_demo.controller;

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.web.bind.annotation.*;

@RestController
@EnableAutoConfiguration
public class Example {

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

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

}

@RestController:是@ResponseBody@Controller的合用注解

4.5、运行主程序测试

控制台打印:

2019-09-19 22:12:26.137  INFO 15156 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-09-19 22:12:26.142  INFO 15156 --- [  restartedMain] c.e.s.SpringBootDemoApplication          : Started SpringBootDemoApplication in 3.602 seconds (JVM running for 6.441)
2019-09-19 22:12:48.004  INFO 15156 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-09-19 22:12:48.005  INFO 15156 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-09-19 22:12:48.015  INFO 15156 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 10 ms

可以看到默认启用的是8080端口,浏览器访问localhost:8080即可访问该项目

HelloWorld.png

4.6、简化部署

<!-- 这个插件,可以将应用打包成一个可执行的jar包 -->
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

在pom文件所在的文件夹执行cmd命令: mvn clean package即可打包成jar包文件

Maven打包.png

将这个应用打成jar包后,直接使用java -jar的命令进行执行

CMD执行.png

5、Hello World探究

5.1、POM文件

5.1.1、父项目

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.8.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

他的父项目是

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.1.8.RELEASE</version>
    <relativePath>../../spring-boot-dependencies</relativePath>
</parent>

他来真正管理Spring Boot应用里面的所有依赖版本;

依赖版本.png

Spring Boot的版本仲裁中心;

以后我们导入依赖默认是不需要写版本;(没有在dependencies里面管理的依赖自然需要声明版本号

5.1.2、启动器

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

spring-boot-starter-web

spring-boot-starterspring-boot场景启动器;spring-boot-starter-web帮我们导入了web模块正常运行所依赖的组件;

Spring Boot将所有的功能场景都抽取出来,做成一个个的starters(启动器),只需要在项目里面引入这些starter相关场景的所有依赖都会导入进来。要用什么功能就导入什么场景的启动器

Spring Boot官方支持的Starter

5.2、主程序类,主入口类


package com.example.spring_boot_demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 *  @SpringBootApplication 来标注一个主程序类,说明这是一个Spring Boot应用
 */
@SpringBootApplication
public class SpringBootDemoApplication {

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

}

@SpringBootApplication: Spring Boot应用中标注在某个类上说明这个类是SpringBoot的主配置类,SpringBoot就应该运行这个类的main方法来启动SpringBoot应用

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
    ...
}

@SpringBootConfiguration:Spring Boot的配置类;标注在某个类上,表示这是一个Spring Boot的配置类;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {

}

@Configuration:配置类上来标注这个注解;

配置类相当于之前的配置文件;配置类也是容器中的一个组件;@Component

SpringBootApplication注解上面的@EnableAutoConfiguration:开启自动配置功能;

以前我们需要配置的东西,Spring Boot帮我们自动配置;@EnableAutoConfiguration告诉SpringBoot开启自动配置功能;这样自动配置才能生效;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
    ...
}

@AutoConfigurationPackage:自动配置包

AutoConfigurationPackage上面的@Import(AutoConfigurationPackages.Registrar.class)

Spring的底层注解@Import,给容器中导入一个组件;导入的组件由AutoConfigurationPackages.Registrar.class将主配置类(@SpringBootApplication标注的类)的所在包及下面所有子包里面的所有组件扫描到Spring容器。

@Import(AutoConfigurationImportSelector.class)来确定给容器中导入组件

AutoConfigurationImportSelector类:导入哪些组件的选择器;

​ 将所有需要导入的组件以全类名的方式返回;这些组件就会被添加到容器中;

​ 会给容器中导入非常多的自动配置类(xxxAutoConfiguration);就是给容器中导入这个场景需要的所有组件,并配置好这些组件

自动配置类.png

有了自动配置类,免去了我们手动编写配置注入功能组件等的工作;

SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class,
				getBeanClassLoader());
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

Spring Boot在启动的时候从类路径下的META-INF/spring.factories中获取EnableAutoConfiguration指定的值,将这些值作为自动配置类导入到容器中,自动配置类就生效,帮我们进行自动配置工作;

以前我们需要自己配置的东西,自动配置类都帮我们;

J2EE的整体整合解决方案和自动配置都在spring-boot-autoconfigure-2.1.8.RELEASE.jar里面了

6、使用Spring Initializer快速创建Spring Boot项目

6.1、IDEA:使用 Spring Initializer快速创建项目

IDE都支持使用Spring的项目创建向导快速创建一个Spring Boot项目;

选择我们需要的模块;向导会联网创建Spring Boot项目;

默认生成的Spring Boot项目;

  • 主程序已经生成好了,我们只需要我们自己的逻辑
  • resources文件夹中目录结构
    • static:保存所有的静态资源;比如说js、css、images;
    • templates:保存所有的模板页面;(Spring Boot默认jar包使用嵌入式的Tomcat,默认不支持JSP页面);可以使用模板引擎(freemarker、thymeleaf);
    • application.properties:Spring Boot应用的配置文件;可以修改一些默认设置;

6.2、STS使用 Spring Starter Project快速创建项目