Spring Boot快速掌握(1):核心技术

2021-03-05 08:28

阅读:401

  •  1)@SpringBootConfiguration注解

           标明该类使用Spring基于Java的注解,Spring Boot推荐使用基于Java而不是XML的配置。查看@SpringBootConfiguration源代码,可以看到它就是对@Configuration进行简单的“包装”,然后取名为SpringBootConfiguration。

           我们对@Configuration注解并不陌生,它就是JavaConfig形式的SpringIoC容器的配置类使用的那个@Configuration。

           其源代码如下:

package org.springframework.boot;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AliasFor;

/**
* Indicates that a class provides Spring Boot application
* {@link Configuration @Configuration}. Can be used as an alternative to the Spring‘s
* standard {@code @Configuration} annotation so that configuration can be found
* automatically (for example in tests).
* 

* Application should only ever include one {

@code @SpringBootConfiguration} and * most idiomatic Spring Boot applications will inherit it from * {@code @SpringBootApplication}. * * @author Phillip Webb * @author Andy Wilkinson * @since 1.4.0 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration public @interface SpringBootConfiguration { /** * Specify whether {@link Bean @Bean} methods should get proxied in order to enforce * bean lifecycle behavior, e.g. to return shared singleton bean instances even in * case of direct {@code @Bean} method calls in user code. This feature requires * method interception, implemented through a runtime-generated CGLIB subclass which * comes with limitations such as the configuration class and its methods not being * allowed to declare {@code final}. *

* The default is {

@code true}, allowing for ‘inter-bean references‘ within the * configuration class as well as for external calls to this configuration‘s * {@code @Bean} methods, e.g. from another configuration class. If this is not needed * since each of this particular configuration‘s {@code @Bean} methods is * self-contained and designed as a plain factory method for container use, switch * this flag to {@code false} in order to avoid CGLIB subclass processing. *

* Turning off bean method interception effectively processes {

@code @Bean} methods * individually like when declared on non-{@code @Configuration} classes, a.k.a. * "@Bean Lite Mode" (see {@link Bean @Bean‘s javadoc}). It is therefore behaviorally * equivalent to removing the {@code @Configuration} stereotype. * @return whether to proxy {@code @Bean} methods * @since 2.2 */ @AliasFor(annotation = Configuration.class) boolean proxyBeanMethods() default true; }

 

  • 2)@EnableAutoConfiguration注解:该注解可以开启自动配置的功能。

           从@EnableAutoConfiguration源代码可以看出,其包含@Import注解。我们知道,@Import注解的主要作用就是借助EnableAutoConfigurationImportSelector将Spring Boot应用所有符合条件的@Configuration配置都加载到当前Spring Boot创建并使用的IoC容器中。

          IoC容器就是我们所说的Spring应用程序上下文ApplicationContext。

          学习过Spring框架就知道,Spring框架提供了很多@Enable开头的注解定义,比如@EnableScheduling、@EnableCaching等。这些@Enable开头的注解都有一个共同的功能,就是借助@Import的支持,收集和注册特定场景相关的bean定义。

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

           其源代码如下:

package org.springframework.boot.autoconfigure;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.support.SpringFactoriesLoader;

/**
* 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. For example, if you
* have {@code tomcat-embedded.jar} on your classpath you are likely to want a
* {@link TomcatServletWebServerFactory} (unless you have defined your own
* {@link ServletWebServerFactory} bean).
* 

* When using {

@link SpringBootApplication @SpringBootApplication}, the auto-configuration * of the context is automatically enabled and adding this annotation has therefore no * additional effect. *

* Auto-configuration tries to be as intelligent as possible and will back-away as you * define more of your own configuration. You can always manually {

@link #exclude()} any * configuration that you never want to apply (use {@link #excludeName()} if you don‘t * have access to them). You can also exclude them via the * {@code spring.autoconfigure.exclude} property. Auto-configuration is always applied * after user-defined beans have been registered. *

* The package of the class that is annotated with {

@code @EnableAutoConfiguration}, * usually via {@code @SpringBootApplication}, has specific significance and is often used * as a ‘default‘. For example, it will be used when scanning for {@code @Entity} classes. * It is generally recommended that you place {@code @EnableAutoConfiguration} (if you‘re * not using {@code @SpringBootApplication}) in a root package so that all sub-packages * and classes can be searched. *

* Auto-configuration classes are regular Spring {

@link Configuration @Configuration} * beans. They are located using the {@link SpringFactoriesLoader} mechanism (keyed * against this class). Generally auto-configuration beans are * {@link Conditional @Conditional} beans (most often using * {@link ConditionalOnClass @ConditionalOnClass} and * {@link ConditionalOnMissingBean @ConditionalOnMissingBean} annotations). * * @author Phillip Webb * @author Stephane Nicoll * @since 1.0.0 * @see ConditionalOnBean * @see ConditionalOnMissingBean * @see ConditionalOnClass * @see AutoConfigureAfter * @see SpringBootApplication */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage @Import(AutoConfigurationImportSelector.class) public @interface EnableAutoConfiguration { String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; /** * Exclude specific auto-configuration classes such that they will never be applied. * @return the classes to exclude */ Class>[] exclude() default {}; /** * Exclude specific auto-configuration class names such that they will never be * applied. * @return the class names to exclude * @since 1.3.0 */ String[] excludeName() default {}; }

 

  • 3)@ComponentScan注解:启动组件扫描

          开发的组件或bean定义能被自动发现并注入到Spring应用程序上下文。比如我们在控制层添加@Controller注解、服务层添加的@Service注解和@Component注解等,这些注解都可以被@ComponentScan注解扫描到。

 

二、Spring Boot配置

1.Spring Boot 自动配置原理

问:Spring Boot自动配置原理是什么?
答:注解 @EnableAutoConfiguration, @Configuration, @ConditionalOnClass 就是自动配置的核心,
  @EnableAutoConfiguration 给容器导入META-INF/spring.factories 里定义的自动配置类。
  筛选有效的自动配置类。
  每一个自动配置类结合对应的 xxxProperties.java 读取配置文件进行自动配置功能

 

2.配置文件

配置文件的作用:修改Spring Boot自动配置的默认值。

Spring Boot使用一个全局配置文件,并且配置文件的名称是固定的。

  • application.properties
  • application.yaml

问:你如何理解 Spring Boot 配置加载顺序?

答:在 Spring Boot 里面,可以使用以下几种方式来加载配置。

          1)properties文件;

          2)YAML文件;

          3)系统环境变量;
          4)命令行参数;
         等等……

 

问:什么是 YAML?YAML 配置的优势在哪里 ?

答:YAML 是一种人类可读的数据序列化语言。它通常用于配置文件。与属性文件相比,如果我们想要在配置文件中添加复杂的属性,YAML 文件就更加结构化,而且更少混淆。可以看出 YAML 具有分层配置数据。

       YAML 现在可以算是非常流行的一种配置文件格式了,无论是前端还是后端,都可以见到 YAML 配置。那么 YAML 配置和传统的 properties 配置相比到底有哪些优势呢?
  1. 配置有序,在一些特殊的场景下,配置有序很关键
  2. 支持数组,数组中的元素可以是基本数据类型也可以是对象
  3. 简洁
      相比 properties 配置文件,YAML 还有一个缺点,就是不支持 @PropertySource 注解导入自定义的 YAML 配置。

 

问:Spring Boot 是否可以使用 XML 配置 ?

答:Spring Boot 推荐使用 Java 配置而非 XML 配置,但是 Spring Boot 中也可以使用 XML 配置,通过 @ImportResource 注解可以引入一个 XML 配置。

 

问:spring boot 核心配置文件是什么?bootstrap.properties 和 application.properties 有何区别 ?

答:单纯做 Spring Boot 开发,可能不太容易遇到 bootstrap.properties 配置文件,但是在结合 Spring Cloud 时,这个配置就会经常遇到了,特别是在需要加载一些远程配置文件的时侯。

       spring boot 核心的两个配置文件:

  • application (. yml 或者 . properties):由ApplicatonContext 加载,用于 spring boot 项目的自动化配置;
  • bootstrap (. yml 或者 . properties):boostrap 由父 ApplicationContext 加载的,比 applicaton 优先加载,配置在应用程序上下文的引导阶段生效。一般来说我们在 Spring Cloud Config 或者 Nacos 中会用到它。且 boostrap 里面的属性不能被覆盖。

 

 3.YAML语法

 

 

 

 

 

 

 

 

 

 

 

 

持续更新中······

 

上一篇:Python练习

下一篇:python生成requirements.txt


评论


亲,登录后才可以留言!