微服务架构-实现技术之具体实现工具与框架2:Spring Boot概览与核心原理

目录

一、Spring Boot概述

1.回顾使用Spring开发WEB应用程序过程

2.新一代开发框架的诞生Spring Boot

编码方面

配置方面

部署方面

监控方面

3.SpringBoot核心功能

4.SpringBoot优缺点

优点:

缺点:

5.SpringBoot几个常用的注解

二、Spring Boot核心原理

@SpringBootApplication讲解

1.@Configuration讲解

2.@ComponentScan讲解

3.@EnableAutoConfiguration讲解(重点)

参考书籍、文献和资料:


推荐将Spring Boot作为实现微服务架构的基础框架。

一、Spring Boot概述

1.回顾使用Spring开发WEB应用程序过程

广泛采用的固定开发模式:通常包括使用Maven、Gradle等工具搭建工程、web.xml定义Spring的DispatcherServlet、完成启动Spring MVC的配置文件、编写响应HTTP请求的Controller以及服务部署到Tomcat Web服务器等步骤。

但是,基于传统Spring框架进行开发的开发过程中,逐渐暴露出一些问题,典型的就是过于复杂和繁重的配置工作。

2.新一代开发框架的诞生Spring Boot

优化上面的开发过程,推动了以Spring Boot为代表的新一代开发框架诞生,Spring Boot采用约定优于配置思想的自动化配置、启动依赖项目自动管理、简化部署并提供监控等功能,是开发过程变得简单。

其核心优势体现在编码、配置、部署、监控等多个方面:

编码方面

只需要在maven中添加依赖并实现一个方法就可以提供微服务架构所推荐的RESTful风格接口。

配置方面

简单化,1>把Spring中基于XML的功能配置方式转换为Java Config;2>把基于*.properties/*.xml文件部署环境配置转换成语言更为强大的*.yml;3>对常见的各种功能组件均提供了各种默认的starter依赖以简化Maven的配置。

部署方面

相较于传统模式下的war包,Spring Boot的部署既包含了业务代码和各种第三方类库,同时也内嵌了HTTP容器。

新的部署方式包结构支持java-jar standalone.jar方式的一键启动,不需要预部署应用服务器,通过默认内嵌Tomcat降低对运行环境的基本要求。

监控方面

基于spring-boot-actuator组件,可以通过RESTful接口以及HATEOAS表现方式获取JVM性能指标、线程工作状态等运行信息。

3.SpringBoot核心功能

  • 独立运行Spring项目

Spring boot 可以以jar包形式独立运行,运行一个Spring Boot项目只需要通过java -jar xx.jar来运行。

  • 内嵌servlet容器

Spring Boot可以选择内嵌Tomcat、jetty或者Undertow,这样我们无须以war包形式部署项目。

  • 提供starter简化Maven配置

spring提供了一系列的start pom来简化Maven的依赖加载,例如,当你使用了spring-boot-starter-web,会自动加入如图5-1所示的依赖包。

  • 自动装配Spring 

SpringBoot会根据在类路径中的jar包,类、为jar包里面的类自动配置Bean,这样会极大地减少我们要使用的配置。

当然,SpringBoot只考虑大多数的开发场景,并不是所有的场景,若在实际开发中我们需要配置Bean,而SpringBoot灭有提供支持,则可以自定义自动配置。

  • 准生产的应用监控

SpringBoot提供基于http ssh telnet对运行时的项目进行监控。

  • 无代码生产和xml配置  

SpringBoot不是借助与代码生成来实现的,而是通过条件注解来实现的,这是Spring4.x提供的新特性。

4.SpringBoot优缺点

优点:

  • 快速构建项目
  • 对主流开发框架的无配置集成
  • 项目可独立运行,无须外部依赖Servlet容器
  • 提供运行时的应用监控
  • 极大的提高了开发、部署效率
  • 与云计算的天然集成

缺点:

  • 如果你不认同spring框架,也许这就是缺点
  • SpringBoot特性
  • 创建独立的Spring项目
  • 内置Tomcat和Jetty容器
  • 提供一个starter POMs来简化Maven配置
  • 提供了一系列大型项目中常见的非功能性特性,如安全、指标,健康检测、外部配置等
  • 完全没有代码生成和xml配置文件

5.SpringBoot几个常用的注解

(1)@RestController和@Controller指定一个类,作为控制器的注解 ,并说明其区别
(2)@RequestMapping方法级别的映射注解,这一个用过Spring MVC的小伙伴相信都很熟悉 
(3)@EnableAutoConfiguration和@SpringBootApplication是类级别的注解,根据maven依赖的jar来自动猜测完成正确的spring的对应配置,只要引入了spring-boot-starter-web的依赖,默认会自动配置Spring MVC和tomcat容器
(4)@Configuration类级别的注解,一般这个注解,我们用来标识main方法所在的类,完成元数据bean的初始化。
(5)@ComponentScan类级别的注解,自动扫描加载所有的Spring组件包括Bean注入,一般用在main方法所在的类上 
(6)@ImportResource类级别注解,当我们必须使用一个xml的配置时,使用@ImportResource和@Configuration来标识这个文件资源的类。 
(7)@Autowired注解,一般结合@ComponentScan注解,来自动注入一个Service或Dao级别的Bean
(8)@Component类级别注解,用来标识一个组件,比如我自定了一个filter,则需要此注解标识之后,Spring Boot才会正确识别。

二、Spring Boot核心原理

   

基于SpringBoot开发模式很简单,比方说通过引入spring-boot-starter-web工程,并在应用程序入口添加@SpringBootApplication注解,就能构建RESTful风格接口,如下,而这在Spring框架中需要通过各种配置和代码才能实现同样的功能。

pom.xml中:

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

应用程序入口:

@SpringBootApplication
@RestController
public class SpringCloudApplication
{
    public static void main(String[] args)
    {
        SpringApplication.run(SpringCloudApplication.class, args);
    }

    @RequestMapping(value = "/login")
    public String login()
    {
        return "Hello Spring Boot!";
    }

}

@SpringBootApplication讲解

我们来解析@SpringBootApplication注解背后的实现原理,源码中@SpringBootApplication注解定义如下:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Configuration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication {
    Class<?>[] exclude() default {};

    String[] excludeName() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackages"
    )
    String[] scanBasePackages() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackageClasses"
    )
    Class<?>[] scanBasePackageClasses() default {};
}

从源代码中得知 @SpringBootApplication 被 @Configuration、@EnableAutoConfiguration、@ComponentScan 注解所修饰,换言之 Springboot 提供了统一的注解来替代以上三个注解,简化程序的配置。下面解释一下各注解的功能:

1.@Configuration讲解

spring文档说明:

@Configuration is a class-level annotation indicating that an object is a source of bean definitions.
@Configuration classes declare beans via public @Bean annotated methods.

@Configuration 是一个类级注释,指示对象是一个bean定义的源。@Configuration 类通过 @bean 注解的公共方法声明bean。

The @Bean annotation is used to indicate that a method instantiates, configures and initializes a new object to be managed by the Spring IoC container.

@Bean 注释是用来表示一个方法实例化,配置和初始化是由 Spring IoC 容器管理的一个新的对象。

通俗的讲 @Configuration 一般与 @Bean 注解配合使用,用 @Configuration 注解类等价与 XML 中配置 beans,用 @Bean 注解方法等价于 XML 中配置 bean。

2.@ComponentScan讲解

spring文档说明:

Configures component scanning directives for use with @Configuration classes. Provides support parallel with Spring XML’s element.

为 @Configuration注解的类配置组件扫描指令。同时提供与 Spring XML’s 元素并行的支持。

Either basePackageClasses() or basePackages() (or its alias value()) may be specified to define specific packages to scan. If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.

无论是 basePackageClasses() 或是 basePackages() (或其 alias 值)都可以定义指定的包进行扫描。如果指定的包没有被定义,则将从声明该注解的类所在的包进行扫描。

Note that the element has an annotation-config attribute;
however, this annotation does not. This is because in almost all cases when using @ComponentScan, 
default annotation config processing (e.g. processing @Autowired and friends) is assumed. 
Furthermore, when using AnnotationConfigApplicationContext, annotation config processors are always registered, 
meaning that any attempt to disable them at the @ComponentScan level would be ignored.

注意, 元素有一个 annotation-config 属性,但是 @ComponentScan 没有。这是因为在使用 @ComponentScan 注解的几乎所有的情况下,默认的注解配置处理是假定的。此外,当使用 AnnotationConfigApplicationContext, 注解配置处理器总会被注册,以为着任何试图在 @ComponentScan 级别是扫描失效的行为都将被忽略。

通俗的讲,@ComponentScan 注解会自动扫描指定包下的全部标有 @Component注解 的类,并注册成bean,当然包括 @Component 下的子注解@Service、@Repository、@Controller。@ComponentScan 注解没有类似 、的属性。

3.@EnableAutoConfiguration讲解(重点)

spring文档说明:

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 应用程序上下文的自动配置,试图猜测和配置您可能需要的bean。自动配置类通常采用基于你的 classpath 和已经定义的 beans 对象进行应用。

The package of the class that is annotated with @EnableAutoConfiguration has specific significance and is often used as a ‘default’.
For example, it will be used when scanning for@Entity classes. 
It is generally recommended that you place@EnableAutoConfiguration in a root package so that all sub-packages and classes can be searched.

被 @EnableAutoConfiguration 注解的类所在的包有特定的意义,并且作为默认配置使用。例如,当扫描 @Entity类的时候它将本使用。通常推荐将 @EnableAutoConfiguration 配置在 root 包下,这样所有的子包、类都可以被查找到。

Auto-configuration classes are regular Spring Configuration beans.
They are located using the SpringFactoriesLoader mechanism (keyed against this class).
Generally auto-configuration beans are @Conditional beans (most often using @ConditionalOnClass and @ConditionalOnMissingBean annotations).

Auto-configuration类是常规的 Spring 配置 Bean。它们使用的是 SpringFactoriesLoader 机制(以 EnableAutoConfiguration 类路径为 key)。

SpringFactoriesLoader 机制: 
SpringFactoriesLoader会查询包含 META-INF/spring.factories 文件的JAR。 当找到spring.factories文件后,SpringFactoriesLoader将查询配置文件命名的属性。EnableAutoConfiguration的 key 值为org.springframework.boot.autoconfigure.EnableAutoConfiguration。根据此 key 对应的值进行 spring 配置。在 spring-boot-autoconfigure.jar文件中,包含一个 spring.factories 文件,内容如下:(截取部分)

# Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer

# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.autoconfigure.BackgroundPreinitializer

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration,\

注意:

使用Spring Boot作为构建微服务的轻量级框架是合适的,但Spring Boot并不包含服务注册和发现机制、外围服务监控、服务熔断和服务治理等功能,提供这些功能的是Spring Cloud。

参考书籍、文献和资料:

【1】郑天民. 微服务设计原理与架构. 北京:人民邮电出版社,2018.

【2】https://blog.csdn.net/qq_35216516/article/details/80529220.

【3】https://blog.csdn.net/claram/article/details/75125749.

【4】http://www.cnblogs.com/exe19/p/5391712.html.

发布了52 篇原创文章 · 获赞 15 · 访问量 133万+

猜你喜欢

转载自blog.csdn.net/xiaofeng10330111/article/details/87271456