SpringBoot2-核心技术+基础入门

第一季:SpringBoot2核心技术-基础入门

1 springboot 的特点

第一个Hello SpringBoot2程序

可以设置maven的setting 中项目编译jdk用1.8

在这里插入图片描述

新建工程 添加SpringBoot父元素,和启动依赖

在这里插入图片描述

在这里插入图片描述
注意一个spring的启动文件(spring-boot-starter-web)就包含很多依赖 比如tomcat junt jackson等
在这里插入图片描述

新建启动类

在这里插入图片描述

controller

在这里插入图片描述

run启动类 浏览器访问

在这里插入图片描述
新建SpringBoot的配置文件
可以修改服务器的端口号,其他配置在官网上找

在这里插入图片描述

SpringBoot的打包

以前都是通过打war包然后放到tomcat上部署运行,spring boot可直接通过FatJar(胖胖的jar),就可把代码运行的环境等一起实现打包。

注意:我在因为这个插件时,不加版本号会报错,具体原因不详。

在这里插入图片描述

通过maven打包

在这里插入图片描述

可以在target中看到一个文件夹

在这里插入图片描述

在本地命令行执行打包好的jar即可启动服务器

在这里插入图片描述
注意点:
● 取消掉cmd的快速编辑模式

1.1、依赖管理

springboot的依赖管理就是通过starter我叫依赖控制器。

依赖管理 这个是我们使用的starter。

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

版本的控制是在他的父项目中

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

starter依赖控制器控制器:分类
几乎声明了所有开发中常用的依赖的版本号,自动版本仲裁机制 开发导入starter场景启动器

1、见到很多 spring-boot-starter-* : *就某种场景
2、只要引入starter,这个场景的所有常规需要的依赖我们都自动引入
3、SpringBoot中版本控制所有支持的场景

https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-starter

4、见到的 *-spring-boot-starter: 第三方为我们提供的简化开发的场景启动器。
5、所有场景启动器最底层的依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter</artifactId>
  <version>2.3.4.RELEASE</version>
  <scope>compile</scope>
</dependency>

无需关注版本号,自动版本仲裁

1、引入依赖默认都可以不写版本
2、引入非版本仲裁的jar,要写版本号。

如果修改默认版本号 比如你数据库用的orale5但是springboot版本控制是8,那么就需要修改。

1、查看spring-boot-dependencies里面规定当前依赖的版本 用的 key。
2、在当前项目里面重写配置

<properties>
    <mysql.version>5.1.43</mysql.version>
</properties>

在这里插入图片描述

查看starter的分析依赖树状图:

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

1.2、自动配置(以下了解即可)

程序需要的组件springboot通过starter导入,它还有自动配置的功能。如

● 自动配好Tomcat

○ 引入Tomcat依赖。
○ 配置Tomcat spring如何配置的往下会设计到

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
      <version>2.3.4.RELEASE</version>
      <scope>compile</scope>
    </dependency>

● 自动配好SpringMVC

○ 引入SpringMVC全套组件
○ 自动配好SpringMVC常用组件(功能)

● 自动配好Web常见功能,如:字符编码问题

○ SpringBoot帮我们配置好了所有web开发的常见场景

● 默认的包结构

我们之前写组件 如@Controller,还需要在bean.xml中配置springmvc的注解扫面,那么springboot是怎么做的呢

○ 主程序所在包及其下面的所有子包里面的组件都会被默认扫描进来
○ 无需以前的包扫描配置
○ 想要改变扫描路径,

注意在主程序包结构外 是扫描不到组件(注解)的。

@SpringBootApplication(scanBasePackages="com.quxingtao")
    ■ 或者@ComponentScan 指定扫描路径

启动类上的@SpringBootApplication等同于以下这三个注解一起的功能

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.quxingtao.boot")

● application.properties配置文件中的各种配置都拥有默认值

○ 默认值配置最终都是映射到某个类上,如:MultipartProperties
○ 如何实现映射?配置文件的值最终会绑定每个类上,这个类会在容器中创建对象

● 按需加载所有自动配置项

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

● …
在这里插入图片描述

2 容器功能(IOC容器)

之前我们是通过bean.xml配置对象到ioc容器

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

现在我们通过配置类

在这里插入图片描述

通过启动类测试组件

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

2.1、组件添加

1、@Configuration

基本使用 当一个类被@Configuration修饰,那么就是一个配置类,这个配置类有两种模式:

Full模式与Lite模式(全配置和轻量级配置)

@Configuration(proxyBeanMethods = true)就是Full模式 反之false即Lite模式

在Full模式下(proxyBeanMethods属性 = true,默认就是true。)则配置类就会被spring代理,所以它也是容器中一个对象,只不过当我们在容器中拿到配置类可以看到它是一个被SpringCGLIB增强的对象。如下图

在这里插入图片描述

注意:
配置类的属性proxyBeanMethods = true时,那么在通过配置类在容器中拿到的bean都是一个对象 单例
proxyBeanMethods = false多例

注意:不通过配置类在容器中拿对象,而是直接在容器中通过方法名拿的话,就与proxyBeanMethods属性无关,在容器中拿出来的对象,本身就是单例。

如下:

proxyBeanMethods默认true情况,返回结果true,
proxyBeanMethods = false,返回结果false
在这里插入图片描述
在这里插入图片描述

综上的例子总结:
配置类的proxyBeanMethods = true时,通过配置类去调用对象时去容器中找组件。
反之调用则会new一个对象。

配置类中组件之间无依赖关系用Lite模式加速容器启动过程,减少判断 配置类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式

示例 最佳实战

/**
 * 1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
 * 2、配置类本身也是组件
 * 3、proxyBeanMethods:代理bean的方法
 *      Full(proxyBeanMethods = true)、【保证每个@Bean方法被调用多少次返回的组件都是单实例的】
 *      Lite(proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的】
 *      组件依赖必须使用Full模式默认。其他默认是否Lite模式
 */
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
public class MyConfig {

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

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


################################@Configuration测试代码如下########################################
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.atguigu.boot")
public class MainApplication {

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

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

        //3、从容器中获取组件
        //这样拿对象跟配置类的proxyBeanMethods = false无关,通过@Bean注解注册到容器,默认也是单例的 返回结果为true.

        Pet tom01 = run.getBean("tom", Pet.class);
        Pet tom02 = run.getBean("tom", Pet.class);
        System.out.println("组件:"+(tom01 == tom02));

        //4、配置类是被增强的对象。com.atguigu.boot.config.MyConfig$$EnhancerBySpringCGLIB$$51f1e1ca@1654a892
        MyConfig bean = run.getBean(MyConfig.class);
        System.out.println(bean);

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

        User user01 = run.getBean("user01", User.class);
        Pet tom = run.getBean("tom", Pet.class);
		//proxyBeanMethods = false时,不回去ioc容器找,返回false
        System.out.println("用户的宠物:"+(user01.getPet() == tom));
    }
}

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

以前的注解一样继续使用,因为和spring是无缝衔接的。

3、@ComponentScan、@Import

/*
 * @Import({User.class, DBHelper.class})
 *      给容器中自动创建出这两个类型的组件、默认组件的名字就是全类名
 *
 */

@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) 
public class MyConfig {
}

@Import 高级用法:

https://www.bilibili.com/video/BV1gW411W7wy?p=8

4、@Conditional

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

条件装配解决的问题:
如有人和宠物两个组件,而两个组件存在依赖关系,注入人组件到容器中时,把宠物组件注入到人的组件中。这时如果宠物组件没有注入到容器中,那么人也不能注入。

=测试条件装配======

@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 == 配置文件
//@ConditionalOnBean(name = "tom") 只有容器中tom名字的组件,这个配置类里的组件才添加到容器中。否则配置类中的代码不执行。
@ConditionalOnMissingBean(name = "tom")
public class MyConfig {


    /**
     * Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注册容器中的单实例对象
     * @return
     */

    @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
    public User user01(){
        User zhangsan = new User("zhangsan", 18);
        //user组件依赖了Pet组件
        zhangsan.setPet(tomcatPet());
        return zhangsan;
    }

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

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

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

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

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

        boolean tom22 = run.containsBean("tom22");
        System.out.println("容器中tom22组件:"+tom22);
    }

2.2、原生配置文件引入

1、@ImportResource

使用场景:比如需要整合原生的配置组件文件,那么spring boot就需要导入bean.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.atguigu.boot.bean.User">
        <property name="name" value="zhangsan"></property>
        <property name="age" value="18"></property>
    </bean>

    <bean id="hehe" class="com.atguigu.boot.bean.Pet">
        <property name="name" value="tomcat"></property>
    </bean>
</beans>
//可以放在主配置类上,那么就会放在IOC容器中 是一个数组,可放多个值。@ImportResource(locations = "classpath:beans.xml")
@ImportResource("classpath:beans.xml")
public class MyConfig {}

======================测试=================
        boolean haha = run.containsBean("haha");
        boolean hehe = run.containsBean("hehe");
        System.out.println("haha:"+haha);//true
        System.out.println("hehe:"+hehe);//true

@PropertySource
导入配置文件中配置的对象。场景:有一个person类,在sources中新建一个person.properties文件为person类中属性赋值。

@PropertySource(value = "classpath:person.properties")
@Component
@Configurtion
public class Person(){}

2.3、配置绑定

1、@Component + @ConfigurationProperties

使用场景:1. 比如我们之前的数据库配置文件datasource.properties,我们需要新建配置文件,然后引入使用。
注意:以下的例子是把javabean中的对象注册到容器中,然后在springboot的配置文件中操作javabean对象。

场景:2.如何使用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。
         }
     }
 }
例子
//只有在容器中的组件,才会拥有SpringBoot提供的强大功能
@Data
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {

    private String brand;//品牌
    private Integer price;//价格

}

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

总结:bean对象通过spring boot的配置文件接管。

2、@EnableConfigurationProperties + @ConfigurationProperties

上面1方式适合于自己写的javabean可以配置在spring boot的配置文件中,那么我们使用第三方的javabean对象,怎么操作呢?
是通过在配置类里(MyConfig)把javabean注册到容器,再通过spring boot的配置文件配置。对比1方法就是用配置类替换@Component

@Data
@ConfigurationProperties(prefix = "mycar")
public class Car {

    private String brand;//品牌
    private Integer price;//价格

}
@Configuration()
@EnableConfigurationProperties(Car.class)
public class MyConfig {

}

在这里插入图片描述

以上两种方式效果是一样的

3、自动配置原理入门

3.1、引导加载自动配置类(通过研究启动类的注解体会)

spring boot启动类中有一个注解@SpringBootApplication,它由以下三个注解组成,那我们就研究这三个注解即可

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
    @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication{
}
1、@SpringBootConfiguration(这是一个配置类)

这个注解里由@Configuration修饰。@Configuration代表当前是一个配置类,那么说明spring
boot的启动文件也是一个配置文件。

2、@ComponentScan(扫描包路径)

指定扫描哪些,Spring注解;

3、@EnableAutoConfiguration(导入127个自动配置类)

里面两个注解,一个是导入启动需要的组件的路径(@AutoConfigurationPackage),另一个是导什么组件@Import(AutoConfigurationImportSelector.class)。
然后会在spring.factorties类中只当的127个全限定类名(也就是自动配置类~~AutoConfigration)全部加载。但不是全部生效,是通过你配置的依赖坐标,通过自动配置类里的@ConditionalXXXclass进行判断是否生效(按需开启)

该注解内部实现

@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
}
1、@AutoConfigurationPackage(导入配置类的规则)
是指定了启动类的包路径(com.atgugui.boot)。然后把这个路径下的所有的组件批量加载
@Import(AutoConfigurationPackages.Registrar.class)  //给容器中导入一个组件
public @interface AutoConfigurationPackage {
}
//利用Registrar给容器中导入一系列组件 就是把启动类下的组件都注册到容器。
//将指定的一个包下的所有组件导入进来?MainApplication 所在包下。com.quxingtao.boot包写的。
2、@Import(AutoConfigurationImportSelector.class)(导入配置类的位置)
1、利用getAutoConfigurationEntry(annotationMetadata);给容器中批量导入springboot启动需要的组件 
2、调用List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes)获取到所有需要导入到容器中的配置类
3、利用工厂加载 Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader);得到所有的组件
4、组件的位置是从META-INF/spring.factories位置来加载一个文件。
  默认扫描我们当前系统里面所有META-INF/spring.factories位置的文件
    spring-boot-autoconfigure-2.3.4.RELEASE.jar包里面也有META-INF/spring.factories

如下就是获取出来的组件
在这里插入图片描述

文件里面写死了spring-boot一启动就要给容器中加载的所有配置类
spring-boot-autoconfigure-2.3.4.RELEASE.jar/META-INF/spring.factories

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.Neo4jRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcTransactionManagerAutoConfiguration,\
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.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration,\
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.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、按需开启自动配置项

@xxxAutoConfiguration,在spring boot中只要是这种形式的注解,就说明这是一个自动配置类。
虽然以上注解帮我们把127个场景的所有自动配置启动的时候默认全部加载。
但是按照条件装配规则(@Conditional),最终会按需配置,就是你导入了哪个报的依赖哪个组件才会生效。

3.3、修改默认配置()

配置文件上传解析器。如果你的名字叫multipartResolver,那么返回@Bean注解注册的resolver,如果不叫multipartResolver(有些用户不规范),也返回resolver。

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

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

@Bean
  @ConditionalOnMissingBean
  public CharacterEncodingFilter characterEncodingFilter() {
    }

自动装配总结:

● SpringBoot先加载所有的自动配置类 @xxxAutoConfiguration ●
每个自动配置类按照条件进行生效,默认都会绑定配置文件指定的值。xxxProperties里面拿。xxxProperties和配置文件进行了绑定,也就是说可以通过spring boot的配置文件配置组件的参数 ● 生效的配置类就会给容器中装配很多组件 ● 只要容器中有这些组件,相当于这些功能就有了 ● 定制化配置
○ 用户直接自己@Bean替换底层的组件 ○ 用户去看这个组件是获取的配置文件什么值就去修改。

xxxproperties文件: 在这里插入图片描述

自动装配的流程:

@xxxAutoConfiguration —> 注册组件 —> 在xxxProperties里面拿值 ---->
可以在application.properties里该值

通过源码配置组件信息

如:我们修改缓存的配置,可以通过源码就能知道怎么配置
在这里插入图片描述
点击去,那么可以看到缓存有关的所有配置都可以通过这个前缀名,在application.properties中配置
在这里插入图片描述

在这里插入图片描述

3.4、最佳实践

● 引入场景依赖

○ https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-starter

● 查看自动配置了哪些(选做)

○ 自己分析,引入场景对应的自动配置一般都生效了
○ 配置文件中debug=true开启自动配置报告。Negative(不生效)\Positive(生效)

● 是否需要修改

○ 参照文档修改配置项
https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#common-application-properties
自己分析。xxxxProperties绑定了配置文件的哪些。
○ 自定义加入或者替换组件
@Bean、@Component。。。
○ 自定义器 XXXXXCustomizer;
○ …

4、开发小技巧

4.1、Lombok

简化JavaBean开发

org.projectlombok lombok

idea中搜索安装lombok插件

===============================简化JavaBean开发===================================
@NoArgsConstructor
//@AllArgsConstructor
@Data
@ToString
@EqualsAndHashCode
public class User {

    private String name;
    private Integer age;

    private Pet pet;

    public User(String name,Integer age){
        this.name = name;
        this.age = age;
    }
}
================================简化日志开发===================================
@Slf4j
@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String handle01(@RequestParam("name") String name){
        
        log.info("请求进来了....");
        
        return "Hello, Spring Boot 2!"+"你好:"+name;
    }
}

4.2、dev-tools

热部署,修改java代码没啥用,就相当于重启,使用于改静态的前端代码还是好用的

 <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>

项目或者页面修改以后:快捷键Ctrl+F9;

4.3、Spring Initailizr(项目初始化向导)

0、选择我们需要的开发场景
在这里插入图片描述
1、自动依赖引入
在这里插入图片描述
3、自动编写好主配置类
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值