SpringBoot2 基础

连接视频

文档地址

一、SpringBoot2 介绍

1、Spring 与 SpringBoot

Spring官网

Spring能做什么
在这里插入图片描述

1.2 Spring的生态

Spring Boot

覆盖了:
web开发
数据访问
安全控制
分布式
消息服务
移动开发
批处理

1.3、Spring5重大升级

1.3.1、响应式编程

在这里插入图片描述

1.3.2、内部源码设计

基于Java8的一些新特性,如:接口默认实现。重新设计源码架构。


2、为什么用SpringBoot

在这里插入图片描述
能快速创建出生产级别的Spring应用
在这里插入图片描述

2.1、SpringBoot优点

在这里插入图片描述
在这里插入图片描述

  • Create stand-alone Spring applications:创建独立Spring应用

  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files):内嵌web服务器

  • Provide opinionated 'starter' dependencies to simplify your build configuration:自动starter依赖,简化构建配置

  • Automatically configure Spring and 3rd party libraries whenever possible:自动配置Spring以及第三方功能

  • Provide production-ready features such as metrics, health checks, and externalized configuration: 提供生产级别的监控、健康检查及外部化配置

  • Absolutely no code generation and no requirement for XML configuration:无代码生成、无需编写XML

SpringBoot是整合Spring技术栈的一站式框架
SpringBoot是简化Spring技术栈的快速开发脚手架

2.2、SpringBoot缺点

  • 人称版本帝,迭代快,需要时刻关注变化
  • 封装太深,内部原理复杂,不容易精通

3、时代背景

3.1、微服务

James Lewis and Martin Fowler (2014) 提出微服务完整概念。https://martinfowler.com/microservices/

在这里插入图片描述

  • 微服务是一种架构风格
  • 一个应用拆分为一组小型服务
  • 每个服务运行在自己的进程内,也就是可独立部署和升级
  • 服务之间使用轻量级HTTP交互
  • 服务围绕业务功能拆分
  • 可以由全自动部署机制独立部署
  • 去中心化,服务自治。服务可以使用不同的语言、不同的存储技术

3.2、分布式

在这里插入图片描述
分布式的困难

• 远程调用
• 服务发现
• 负载均衡
• 服务容错
• 配置管理
• 服务监控
• 链路追踪
• 日志管理
• 任务调度
• …

分布式的解决

  • SpringBoot + SpringCloud

在这里插入图片描述

3.3、云原生

原生应用如何上云。 Cloud Native

上云的困难

  • 服务自愈
  • 弹性伸缩
  • 服务隔离
  • 自动化部署
  • 灰度发布
  • 流量治理

上云的解决

在这里插入图片描述


4、如何学习SpringBoot

4.1、官网文档架构

SpringBoot文档

SpringBoot中文文档

在这里插入图片描述
在这里插入图片描述

查看版本新特性

在这里插入图片描述



二、SpringBoot2 入门

1、系统要求

  • Java 8 & 兼容java14 .
  • Maven 3.3+
  • idea 2019.1.2

1.1、maven设置

maven目录conf下settings.xml文件设置

<mirrors>
      <mirror>
        <id>nexus-aliyun</id>
        <mirrorOf>central</mirrorOf>
        <name>Nexus aliyun</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public</url>
      </mirror>
  </mirrors>
 
  <profiles>
         <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>
  </profiles>

2、HelloWorld

需求:浏览发送/hello请求,响应 Hello,Spring Boot 2

2.1 创建maven工程

boot-01-helloworld 服务

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2.2、引入依赖

pom文件

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

    <groupId>com.zzp</groupId>
    <artifactId>boot-01-helloworld</artifactId>
    <version>1.0-SNAPSHOT</version>

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


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

</project>

2.3、创建主程序

package com.zzp.boot;

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

/**
 * 主启动类
 * 这是一个SpringBoot应用
 */
@SpringBootApplication
public class MainAppliction {

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

2.4、编写业务

package com.zzp.boot.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//@Controller
//@ResponseBody
@RestController
public class HelloController {


    @RequestMapping("/hello")
    public String headlero1(){
        return "Hello SpringBoot 2!";
    }
}

2.5、测试

直接运行main方法

在这里插入图片描述
浏览器访问:http://localhost:8080/hello

在这里插入图片描述

2.6、简化配置

官网配置信息

resources目录下创建文件,application.properties配置文件,指定访问端口号:

server.port=8081

重新启动:
浏览器访问:http://localhost:8081/hello

在这里插入图片描述

2.7、简化部署

pom文件添加

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

使用idea的Maven工具,把项目打成jar包,直接在目标服务器执行即可。

在这里插入图片描述

在这里插入图片描述

在目录其命令下使用cmd,java 命令启动

java -jar boot-01-helloworld-1.0-SNAPSHOT.jar

三、了解自动配置原理

1、SpringBoot特点

1.1、依赖管理

  • 父项目做依赖管理
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
    </parent>

他的父项目
 <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.5.0</version>
  </parent>

几乎声明了所有开发中常用的依赖的版本号,自动版本仲裁机制
  • 开发导入starter场景启动器
1、见到很多 spring-boot-starter-* : *就某种场景

2、只要引入starter,这个场景的所有常规需要的依赖我们都自动引入

3、SpringBoot所有支持的场景
https://docs.spring.io/spring-boot/docs/current/reference/html/using.html#using.build-systems.starters

4、见到的  *-spring-boot-starter: 第三方为我们提供的简化开发的场景启动器。

5、所有场景启动器最底层的依赖
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter</artifactId>
  <version>2.5.0</version>
  <scope>compile</scope>
</dependency>
  • 无需关注版本号,自动版本仲裁
1、引入依赖默认都可以不写版本

2、引入非版本仲裁的jar,要写版本号
  • 可以修改默认版本号
1、查看spring-boot-dependencies里面规定当前依赖的版本 用的 key。

2、在当前项目里面重写配置
    <properties>
        <mysql.version>5.1.43</mysql.version>
    </properties>

1.2、自动配置

  • 自动配好Tomcat
    • 引入Tomcat依赖。
    • 配置Tomcat
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
      <version>2.5.0</version>
      <scope>compile</scope>
    </dependency>
  • 自动配好SpringMVC

    • 引入SpringMVC全套组件
    • 自动配好SpringMVC常用组件(功能)
  • 自动配好Web常见功能,如:字符编码问题

    • SpringBoot帮我们配置好了所有web开发的常见场景
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.3.7</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.3.7</version>
      <scope>compile</scope>
    </dependency>

在启动类查看 IOC容器组件:

@SpringBootApplication
public class MainAppliction {

    public static void main(String[] args) {
        //1、返回我们 IOC容器
        ConfigurableApplicationContext context = SpringApplication.run(MainAppliction.class, args);

        //2、查看容器里面的组件
        String[] definitionNames = context.getBeanDefinitionNames();
        for (String name : definitionNames) {
            System.out.println("组件=====>" + name);
        }
    }
}

执行:

组件=====>org.springframework.context.annotation.internalConfigurationAnnotationProcessor
组件=====>org.springframework.context.annotation.internalAutowiredAnnotationProcessor
组件=====>org.springframework.context.annotation.internalCommonAnnotationProcessor
组件=====>org.springframework.context.event.internalEventListenerProcessor
组件=====>org.springframework.context.event.internalEventListenerFactory
组件=====>mainAppliction
组件=====>org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory
组件=====>helloController
组件=====>org.springframework.boot.autoconfigure.AutoConfigurationPackages
组件=====>org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration
组件=====>propertySourcesPlaceholderConfigurer
组件=====>org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration$TomcatWebSocketConfiguration
组件=====>websocketServletWebServerCustomizer
组件=====>org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration
组件=====>org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration$EmbeddedTomcat
组件=====>tomcatServletWebServerFactory
组件=====>org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration
组件=====>servletWebServerFactoryCustomizer
组件=====>tomcatServletWebServerFactoryCustomizer
组件=====>org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor
组件=====>org.springframework.boot.context.internalConfigurationPropertiesBinderFactory
组件=====>org.springframework.boot.context.internalConfigurationPropertiesBinder
组件=====>org.springframework.boot.context.properties.BoundConfigurationProperties
组件=====>org.springframework.boot.context.properties.EnableConfigurationPropertiesRegistrar.methodValidationExcludeFilter
组件=====>server-org.springframework.boot.autoconfigure.web.ServerProperties
组件=====>webServerFactoryCustomizerBeanPostProcessor
组件=====>errorPageRegistrarBeanPostProcessor
组件=====>org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletConfiguration
组件=====>dispatcherServlet
组件=====>spring.mvc-org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties
组件=====>org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletRegistrationConfiguration
组件=====>dispatcherServletRegistration
组件=====>org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration
组件=====>org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration
组件=====>taskExecutorBuilder
组件=====>applicationTaskExecutor
组件=====>spring.task.execution-org.springframework.boot.autoconfigure.task.TaskExecutionProperties
组件=====>org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration
组件=====>error
组件=====>beanNameViewResolver
组件=====>org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration
组件=====>conventionErrorViewResolver
组件=====>spring.web-org.springframework.boot.autoconfigure.web.WebProperties
组件=====>spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties
组件=====>org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
组件=====>errorAttributes
组件=====>basicErrorController
组件=====>errorPageCustomizer
组件=====>preserveErrorControllerTargetClassPostProcessor
组件=====>org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration
组件=====>requestMappingHandlerAdapter
组件=====>requestMappingHandlerMapping
组件=====>welcomePageHandlerMapping
组件=====>localeResolver
组件=====>themeResolver
组件=====>flashMapManager
组件=====>mvcConversionService
组件=====>mvcValidator
组件=====>mvcContentNegotiationManager
组件=====>mvcPatternParser
组件=====>mvcUrlPathHelper
组件=====>mvcPathMatcher
组件=====>viewControllerHandlerMapping
组件=====>beanNameHandlerMapping
组件=====>routerFunctionMapping
组件=====>resourceHandlerMapping
组件=====>mvcResourceUrlProvider
组件=====>defaultServletHandlerMapping
组件=====>handlerFunctionAdapter
组件=====>mvcUriComponentsContributor
组件=====>httpRequestHandlerAdapter
组件=====>simpleControllerHandlerAdapter
组件=====>handlerExceptionResolver
组件=====>mvcViewResolver
组件=====>mvcHandlerMappingIntrospector
组件=====>viewNameTranslator
组件=====>org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter
组件=====>defaultViewResolver
组件=====>viewResolver
组件=====>requestContextFilter
组件=====>org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration
组件=====>formContentFilter
组件=====>org.springframework.boot.autoconfigure.aop.AopAutoConfiguration$ClassProxyingConfiguration
组件=====>forceAutoProxyCreatorToUseClassProxying
组件=====>org.springframework.boot.autoconfigure.aop.AopAutoConfiguration
组件=====>org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration
组件=====>applicationAvailability
组件=====>org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$Jackson2ObjectMapperBuilderCustomizerConfiguration
组件=====>standardJacksonObjectMapperBuilderCustomizer
组件=====>spring.jackson-org.springframework.boot.autoconfigure.jackson.JacksonProperties
组件=====>org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfiguration
组件=====>jacksonObjectMapperBuilder
组件=====>org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$ParameterNamesModuleConfiguration
组件=====>parameterNamesModule
组件=====>org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfiguration
组件=====>jacksonObjectMapper
组件=====>org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
组件=====>jsonComponentModule
组件=====>org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration
组件=====>org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration
组件=====>lifecycleProcessor
组件=====>spring.lifecycle-org.springframework.boot.autoconfigure.context.LifecycleProperties
组件=====>org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration
组件=====>stringHttpMessageConverter
组件=====>org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration
组件=====>mappingJackson2HttpMessageConverter
组件=====>org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration
组件=====>org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration
组件=====>messageConverters
组件=====>org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration
组件=====>spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties
组件=====>org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration
组件=====>spring.sql.init-org.springframework.boot.autoconfigure.sql.init.SqlInitializationProperties
组件=====>org.springframework.boot.sql.init.dependency.DatabaseInitializationDependencyConfigurer$DependsOnDatabaseInitializationPostProcessor
组件=====>org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration
组件=====>scheduledBeanLazyInitializationExcludeFilter
组件=====>taskSchedulerBuilder
组件=====>spring.task.scheduling-org.springframework.boot.autoconfigure.task.TaskSchedulingProperties
组件=====>org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration
组件=====>restTemplateBuilderConfigurer
组件=====>restTemplateBuilder
组件=====>org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration$TomcatWebServerFactoryCustomizerConfiguration
组件=====>tomcatWebServerFactoryCustomizer
组件=====>org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration
组件=====>org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration
组件=====>characterEncodingFilter
组件=====>localeCharsetMappingsCustomizer
组件=====>org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration
组件=====>multipartConfigElement
组件=====>multipartResolver
组件=====>spring.servlet.multipart-org.springframework.boot.autoconfigure.web.servlet.MultipartProperties
组件=====>org.springframework.aop.config.internalAutoProxyCreator
  • 默认的包结构
    • 主程序所在包及其下面的所有子包里面的组件都会被默认扫描进来
    • 无需以前的包扫描配置
    • 想要改变扫描路径,@SpringBootApplication(scanBasePackages="com.zzp")
      • 或者@ComponentScan 指定扫描路径
@SpringBootApplication
等同于
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.zzp.boot")
  • 各种配置拥有默认值

    • 默认配置最终都是映射到某个类上,如:MultipartProperties
    • 配置文件的值最终会绑定每个类上,这个类会在容器中创建对象
  • 按需加载所有自动配置项

    • 非常多的starter
    • 引入了哪些场景这个场景的自动配置才会开启
    • SpringBoot所有的自动配置功能都在spring-boot-autoconfigure 包里面
  • 还有更多功能…

2、容器功能

2.1、组件添加

1、@Configuration

  • 基本使用
  • Full模式与Lite模式

示例:

配置 类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断

配置类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式

@Configuration注解:

1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的

2、配置类本身也是组件

3、proxyBeanMethods:代理bean的方法

  • Full(proxyBeanMethods = true),
  • Lite(proxyBeanMethods = false)
  • 组件依赖

代码演示:

/**
 * 用户
 */
public class User {
    private String name;
    private Integer age;
    private Pet pet;

    public User() {
    }

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public Pet getPet() {
        return pet;
    }

    public void setPet(Pet pet) {
        this.pet = pet;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", pet=" + pet +
                '}';
    }
}
/**
 * 宠物
 */
public class Pet {
    private String name;

    public Pet(String name) {
        this.name = name;
    }

    public Pet() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Pet{" +
                "name='" + name + '\'' +
                '}';
    }
}

配置类,添加@Configuration注解

/**
 * 1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
 * 2、配置类本身也是组件
 * 3、proxyBeanMethods:代理bean的方法
 *      Full(proxyBeanMethods = true),
 *      Lite(proxyBeanMethods = false)
 *      组件依赖
 */
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类  == xml配置文件
public class MyConfig {

    /**
     * 外部无论对配置类的这个组件注册方法调用多少次获取的都是之前注册容器中单实例
     * @return
     */
    @Bean //给容器中添加组件。以方法名作为组件id。返回类型就是组件类型。返回的值,就是组件在容器中实例
    public User user01(){
        User user = new User("xiaoming", 18);
        //user组件依赖Pet组件  -- proxyBeanMethods = true
        user.setPet(tomcatPet());
        return user;
    }

    @Bean("tom") //自定义id
    public Pet tomcatPet(){
        return new Pet("tomcat");
    }
}

主启动类,输出控制台:

/**
 * 主启动类;主配置类
 * 这是一个SpringBoot应用
 */
@SpringBootApplication
public class MainAppliction {

    public static void main(String[] args) {
        //1、返回我们 IOC容器
        ConfigurableApplicationContext context = SpringApplication.run(MainAppliction.class, args);

        //2、查看容器里面的组件
        String[] definitionNames = context.getBeanDefinitionNames();
        for (String name : definitionNames) {
            System.out.println("组件=====>" + name);
        }

        //3、从容器中获取组件
        Pet tom01 = context.getBean("tom", Pet.class);
        Pet tom02 = context.getBean("tom", Pet.class);
        System.out.println("组件(tom):" + (tom01 == tom02));

        // 配置类本身也是容器
        // 4、com.zzp.boot.config.MyConfig$$EnhancerBySpringCGLIB$$5666ed9@35f8a9d3
        MyConfig bean = context.getBean(MyConfig.class);
        System.out.println("bean=" + bean);

        //如果@Configuration(proxyBeanMethods = true)代理对象调用方法。SpringBoot总会检查这个组件是否在容器中有。
        // 保持组件单实例
        User user1 = bean.user01();
        User user2 = bean.user01();
        System.out.println("user1==user2:" + (user1==user2));

        User userPet = context.getBean("user01", User.class);
        Pet tom = context.getBean("tom", Pet.class);

        System.out.println("用户的错误:" + (userPet.getPet() == tom));

    }
}

执行:
在这里插入图片描述
在这里插入图片描述

2、@Bean@Component@Controller@Service@Repository

3、@ComponentScan@Import

@Import:给容器导入组件

/**  
 *	@Import({User.class, DBHelper.class})
 *      给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
 */
@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类  == xml配置文件
public class MyConfig {...}

测试:

/**
 * 主启动类;主配置类
 * 这是一个SpringBoot应用
 */
@SpringBootApplication
public class MainAppliction {

    public static void main(String[] args) {
		....

        //5、获取组件
        String[] beanNamesForType = context.getBeanNamesForType(User.class);
        System.out.println("=========");
        for (String s : beanNamesForType) {
            System.out.println(s);
        }
        DBHelper dbHelper = context.getBean(DBHelper.class);
        System.out.println("dbHelper="+ dbHelper);
    }
}

执行:
在这里插入图片描述

@Import 高级用法


4、@Conditional

条件装配:满足Conditional指定的条件,则进行组件注入

找到该类,然后快捷键 Ctrl + h
在这里插入图片描述

先测试配置类有无@Bean的情况下

@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类  == xml配置文件
public class MyConfig {

    /**
     * 外部无论对配置类的这个组件注册方法调用多少次获取的都是之前注册容器中单实例
     * @return
     */
    @Bean //给容器中添加组件。以方法名作为组件id。返回类型就是组件类型。返回的值,就是组件在容器中实例
    public User user01(){
    	...
    }

//    @Bean("tom") //自定义id
    public Pet tomcatPet(){
        return new Pet("tomcat");
    }
}

启动类:(把先前的代码注释)

@SpringBootApplication
public class MainAppliction {

    public static void main(String[] args) {
        //1、返回我们 IOC容器
        ConfigurableApplicationContext context = SpringApplication.run(MainAppliction.class, args);

		....
//        DBHelper dbHelper = context.getBean(DBHelper.class);
//        System.out.println("dbHelper="+ dbHelper);


        boolean tom = context.containsBean("tom");
        System.out.println("容器中tom组件:"+tom);
        boolean user01 = context.containsBean("user01");
        System.out.println("容器中user01组件:"+user01);

    }
}

执行:
在这里插入图片描述

ConditionalOnBean(条件装配)实例
@ConditionalOnBean(name = "tom") 当bean满足有 tom 时才装配

@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类  == xml配置文件
@ConditionalOnBean(name = "tom")
public class MyConfig {

    /**
     * 外部无论对配置类的这个组件注册方法调用多少次获取的都是之前注册容器中单实例
     * @return
     */
    @Bean //给容器中添加组件。以方法名作为组件id。返回类型就是组件类型。返回的值,就是组件在容器中实例
    public User user01(){
        User user = new User("xiaoming", 18);
        //user组件依赖Pet组件  -- proxyBeanMethods = true
        user.setPet(tomcatPet());
        return user;
    }

    @Bean("tom22")
    public Pet tomcatPet(){
        return new Pet("tomcat");
    }
}

测试:

    public static void main(String[] args) {
        //1、返回我们 IOC容器
        ConfigurableApplicationContext context = SpringApplication.run(MainAppliction.class, args);

        //2、查看容器里面的组件
        String[] definitionNames = context.getBeanDefinitionNames();
        for (String name : definitionNames) {
            System.out.println("组件=====>" + name);
        }

        boolean tom = context.containsBean("tom");
        System.out.println("容器中tom组件:"+tom);
        boolean user01 = context.containsBean("user01");
        System.out.println("容器中user01组件:"+user01);
        boolean tom22 = context.containsBean("tom22");
        System.out.println("容器中tom22组件:"+tom22);

    }

执行:
在这里插入图片描述
@ConditionalOnMissingBean(当条件没有XX才装配)实例

@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类  == xml配置文件
//@ConditionalOnBean(name = "tom")
@ConditionalOnMissingBean(name = "tom")
public class MyConfig {...}

使用上面main方法,执行:
在这里插入图片描述


2.2、原生配置文件引入

1、@ImportResource:导入资源

在项目 resources目录下新建xml文件beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="haha" class="com.zzp.boot.bean.User">
        <property name="name" value="xiaoming"></property>
        <property name="age" value="18"></property>
    </bean>

    <bean id="hehe" class="com.zzp.boot.bean.Pet">
        <property name="name" value="tomcat"></property>
    </bean>
</beans>

配置类添加@ImportResource注解指定哪个xml文件

@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类  == xml配置文件
//@ConditionalOnBean(name = "tom")
@ConditionalOnMissingBean(name = "tom")
@ImportResource("classpath:beans.xml")
public class MyConfig {...}

main方法:

    public static void main(String[] args) {
        //1、返回我们 IOC容器
        ConfigurableApplicationContext context = SpringApplication.run(MainAppliction.class, args);

        //2、查看容器里面的组件
        String[] definitionNames = context.getBeanDefinitionNames();
        for (String name : definitionNames) {
            System.out.println("组件=====>" + name);
        }

        boolean haha = context.containsBean("haha");
        boolean hehe = context.containsBean("hehe");
        System.out.println("haha:"+haha);
        System.out.println("hehe:"+hehe);
    }

执行:
在这里插入图片描述


2.3、配置绑定

如何使用Java读取到properties文件中的内容,并且把它封装到JavaBean中,以供随时使用;

public class getProperties {
     public static void main(String[] args) throws FileNotFoundException, IOException {
         Properties pps = new Properties();
         pps.load(new FileInputStream("a.properties"));
         Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
         while(enum1.hasMoreElements()) {
             String strKey = (String) enum1.nextElement();
             String strValue = pps.getProperty(strKey);
             System.out.println(strKey + "=" + strValue);
             //封装到JavaBean。
         }
     }
 }

1、@Component + @ConfigurationProperties

@ConfigurationProperties:注解配置

创建实体Car,添加@Component@ConfigurationProperties注解

/**
 * 只有在容器中的组件,才会拥有SpringBoot通过的强大功能 配置绑定
 */
@Component //加入容器中
@ConfigurationProperties(prefix = "mycar") // prefix:代表配置文件的前缀字符串
public class Car {
    private String brand;
    private Integer price;

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                ", price=" + price +
                '}';
    }
}

application.properties配置文件添加配置

server.port=8081


mycar.brand=BYD
mycar.price=10000

controller层添加访问接口:

@RestController
public class HelloController {

    @Autowired
    private Car car;

    @RequestMapping("/car")
    public Car car(){
        return car;
    }
}

启动,测试访问:http://localhost:8081/car
在这里插入图片描述

2、@EnableConfigurationProperties + @ConfigurationProperties

使用@EnableConfigurationProperties + @ConfigurationProperties方式配置绑定

//@Component //加入容器中
@ConfigurationProperties(prefix = "mycar") // prefix:代表配置文件的前缀字符串
public class Car {..}

在配置添加@EnableConfigurationProperties注解:

  • 开启指定类属性配置绑定功能
  • 把这个指定类这个组件自动注册到容器中
@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类  == xml配置文件
//@ConditionalOnBean(name = "tom")
@ConditionalOnMissingBean(name = "tom")
@ImportResource("classpath:beans.xml")
@EnableConfigurationProperties(Car.class)// 1、开启Car属性配置绑定功能 2、把这个Car这个组件自动注册到容器中
public class MyConfig {...}

重启,再次访问:http://localhost:8081/car

在这里插入图片描述

3、自动配置原理入门

3.1、引导加载自动配置类

SpringBootApplication注解类

@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 {...}

1、@SpringBootConfiguration

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

@Configuration:代表当前是一个配置类

2、@ComponentScan

指定扫描哪些包,Spring注解;

3、@EnableAutoConfiguration(核心)

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

    自动配置包,指定了默认的包规则

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Inherited
    @Import({Registrar.class})//给容器中导入一个组件
    public @interface AutoConfigurationPackage {....}
    

    利用Registrar给容器中导入一下列组件
    将指定的一个包下的所有组件导入进来,MainAppliction(启动类) 所在包下
    在这里插入图片描述

  2. @Import(AutoConfigurationImportSelector.class)

    public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {
    	....
        public String[] selectImports(AnnotationMetadata annotationMetadata) {
            if (!this.isEnabled(annotationMetadata)) {
                return NO_IMPORTS;
            } else {
                AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(annotationMetadata);
                return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
            }
        }
        .....
     }
    

①利用selectImports(AnnotationMetadata annotationMetadata),给容器中批量导入一下组件
List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);获取到所有需要导入到容器中的配置类
在这里插入图片描述

Map<String, List<String>> loadSpringFactories(ClassLoader classLoader)得到所有的组件

getCandidateConfigurations()里面调用SpringFactoriesLoader.loadFactoryNames()方法
在这里插入图片描述
在这里插入图片描述
里面调用loadSpringFactories()方法
在这里插入图片描述

④从Enumeration urls = classLoader.getResources("META-INF/spring.factories")位置来加载一个文件,默认扫描我们当前系统里面所有META-INF/spring.factories位置的文件,
spring-boot-autoconfigure-2.5.0.jar包里面也有META-INF/spring.factories
在这里插入图片描述
在这里插入图片描述
文件里面写死了spring-boot一启动就要给容器中加载的所有配置类
spring-boot-autoconfigure-2.5.0.jar/META-INF/spring.factories

# 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.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
org.springframework.boot.autoconfigure.neo4j.Neo4jAutoConfiguration,\
org.springframework.boot.autoconfigure.netty.NettyAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration,\
org.springframework.boot.autoconfigure.r2dbc.R2dbcTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.security.rsocket.RSocketSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration,\
org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\
org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration

3.2、按需开启自动配置项

虽然我们131个场景的所有自动配置启动的时候默认全部加载。
xxxxAutoConfiguration
按照条件装配规则(@Conditional),最终会按需配置。

3.3、修改默认配置

@AutoConfigureOrder(-2147483648)
@Configuration(
    proxyBeanMethods = false
)
@ConditionalOnWebApplication(
    type = Type.SERVLET
)
@ConditionalOnClass({DispatcherServlet.class})
@AutoConfigureAfter({ServletWebServerFactoryAutoConfiguration.class})
public class DispatcherServletAutoConfiguration {
		... 
		//给容器中加入了文件上传解析器;
		@Bean
        @ConditionalOnBean({MultipartResolver.class})//容器中有这个类型组件
        @ConditionalOnMissingBean(
            name = {"multipartResolver"}
        ) //容器中没有这个名字 multipartResolver 的组件
        public MultipartResolver multipartResolver(MultipartResolver resolver) {
        	//给@Bean标注的方法传入了对象参数,这个参数的值就会从容器中找。
            //SpringMVC multipartResolver。防止有些用户配置的文件上传解析器不符合规范
            // Detect if the user has created a MultipartResolver but named it incorrectly
            return resolver;
        }        

}

SpringBoot默认会在底层配好所有的组件。但是如果用户自己配置了以用户的优先

@Configuration(
    proxyBeanMethods = false
)
@EnableConfigurationProperties({ServerProperties.class})
@ConditionalOnWebApplication(
    type = Type.SERVLET
)
@ConditionalOnClass({CharacterEncodingFilter.class})
@ConditionalOnProperty(
    prefix = "server.servlet.encoding",
    value = {"enabled"},
    matchIfMissing = true
)
public class HttpEncodingAutoConfiguration {
	...
    @Bean
    @ConditionalOnMissingBean//如果容量不存在bean才创建
    public CharacterEncodingFilter characterEncodingFilter() {
        CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
        filter.setEncoding(this.properties.getCharset().name());
        filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.REQUEST));
        filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.RESPONSE));
        return filter;
    }	


}

可以自定义配置:

@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类  == xml配置文件
//@ConditionalOnBean(name = "tom")
@ConditionalOnMissingBean(name = "tom")
@ImportResource("classpath:beans.xml")
@EnableConfigurationProperties(Car.class)// 1、开启Car属性配置绑定功能 2、把这个Car这个组件自动注册到容器中
public class MyConfig {

	....

    @Bean
    public CharacterEncodingFilter characterEncodingFilter() {
        //todo--
        return null;
    }
}

总结:

  • SpringBoot先加载所有的自动配置类 xxxxxAutoConfiguration

  • 每个自动配置类按照条件进行生效,默认都会绑定配置文件指定的值。xxxxProperties里面拿。xxxProperties和配置文件进行了绑定

  • 生效的配置类就会给容器中装配很多组件

  • 只要容器中有这些组件,相当于这些功能就有了

  • 定制化配置

    • 用户直接自己@Bean替换底层的组件
    • 用户去看这个组件是获取的配置文件什么值就去修改。

xxxxxAutoConfiguration —> 组件 —> xxxxProperties里面拿值 ----> application.properties


3.4、最佳实践

在这里插入图片描述
执行启动类:查看控制台

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

修改spring的启动图标,使用定义图片(文本)

第一种:替换默认的banner文件(图片或者文本)
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

启动:

在这里插入图片描述

第二种:在配置文件指定图片(文本)地址:

spring.banner.image.location=classpath:123.jpg

在这里插入图片描述
启动:
在这里插入图片描述


  • 参照文档修改配置项
    • @Bean@Component。。。

  • 自定义器 XXXXXCustomizer

4、开发小技巧

4.1、Lombok

简化JavaBean开发,
spring-boot-starter-parentspring-boot-dependencies可以看到有Lombok的版本号和依赖
在这里插入图片描述
在这里插入图片描述
在pom文件添加依赖

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

在idea装上lombok插件
在这里插入图片描述
使用实体类上添加@Data注解

import lombok.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 只有在容器中的组件,才会拥有SpringBoot通过的强大功能 配置绑定
 */
@ToString // toString
@Data //get set
@AllArgsConstructor //全参构造器
@NoArgsConstructor //无参构造器
@Component //加入容器中
@EqualsAndHashCode //重写equals和hashCode
@ConfigurationProperties(prefix = "mycar") // prefix:代表配置文件的前缀字符串
public class Car {
    private String brand;
    private Integer price;

}

简化日志开发,使用@Slf4j注解,log.info()级别输出

@Slf4j
@RestController
public class HelloController {

    @Autowired
    private Car car;

    @RequestMapping("/hello")
    public String headlero1(){
        log.info("请求进来了......");
        return "Hello SpringBoot 2!";
    }
}

测试:
在这里插入图片描述

4.2、dev-tools

热部署,在启动后,如果修改代码后自动重启:项目或者页面修改以后,或者快捷键:Ctrl+F9;

pom添加依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
4.3、Spring Initailizr(项目初始化向导)

在这里插入图片描述
默认是使用https://start.spring.io/地址,但可能有些电脑连接不上,可以使用阿里的镜像网址:https://start.aliyun.com/

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个用于构建独立的、生产级别的Spring应用程序的框架。它简化了Spring应用程序的配置和部署过程,提供了一种快速开发的方式。 Spring Boot基础理论包括以下几个方面: 1. 自动配置(Auto-configuration):Spring Boot通过自动配置来减少开发人员的工作量。它根据应用程序的依赖关系自动配置Spring应用程序的各个组件,如数据库连接、Web服务器等。开发人员只需要添加相应的依赖,Spring Boot就会根据这些依赖自动配置应用程序。 2. 起步依赖(Starter Dependencies):Spring Boot提供了一系列的起步依赖,这些依赖包含了常用的功能模块,如Web开发、数据库访问、安全认证等。开发人员只需要添加相应的起步依赖,就可以快速引入所需的功能模块。 3. 嵌入式容器(Embedded Container):Spring Boot内置了多个嵌入式容器,如Tomcat、Jetty等。开发人员可以选择其中一个作为应用程序的Web服务器,无需额外配置。 4. 外部化配置(Externalized Configuration):Spring Boot支持将应用程序的配置信息外部化,可以使用属性文件、YAML文件、环境变量等方式进行配置。这样可以使配置更加灵活,方便在不同环境中进行部署。 5. Actuator:Spring Boot提供了Actuator模块,可以监控和管理应用程序的运行状态。通过Actuator,可以查看应用程序的健康状况、性能指标等信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值