springboot基本注解自动配置原理

一、总结与计划

1.1 总结

  • 上午:

    • ftp文件上传

      • 为什么要使用ftp上传(图)

      • linux要开启vsftpd服务

      • Java代码实现

    • 项目打包部署

  • 下午:

    • SpringBoot介绍

    • 第一个SpringBoot应用

      • 搭建

        扫描二维码关注公众号,回复: 11724452 查看本文章
      • 项目结构

      • 运行

    • 自定义banner

1.2 计划

  • 全局配置文件

  • Java 配置方式

  • Starter POM

  • SpringBoot是如何帮助我们完成自动配置?

  • SpringBoot常用注解

  • 日志管理

  • 基于SpringBoot的单元测试

  • 统一异常管理

二、SpringBoot的全局配置

2.1 创建SpringBoot应用

2.1.1 使用IDEA的Spring Initializr

限制:如果网络不够流畅,会导致Spring Initializr无法加载

2.1.2 使用在线生成SpringBoot应用

地址:https://start.spring.io/

 

2.2 如果在idea中同时管理多个项目

  • 将创建的多个项目存放在同一个目录下

     
  • 使用IDEA打开的时候,直接打开目录(不是目录中的项目)

     
  • 在IDEA中将目录下的项目添加到Maven管理

    • help--find Action--输入‘Maven’--点击‘Add Maven Project’ (选择项目的pom文件)

       

2.3 全局配置文件

  • SpringBoot项目使用了一个全局配置文件application.properties进行项目相关的配置

  • 如果SpringBoot默认的设置无法满足我们的需求,就可以在application.properties来进行修改

    # application.properties文件中的配置的 key 必须遵守 SpringBoot的要求
    server.port=8081
    server.servlet.context-path=/demo2
  • Spring Boot默认的属性设置:

    参考:附-SpringBoot默认配置.pdf

  • 全局配置文件的格式也支持yml,并且在企业开发中通常使用yml格式进行配置(yaml语言),与properties对比如下:

    • application.properties

      server.port=8081
      server.servlet.context-path=/demo2
      spring.datasource.url=jdbc:mysql://localhost:3306/test
      spring.datasource.username=root
      spring.datasource.password=admin123
      spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    • application.yml

      server:
        port: 8082
        servlet:
          context-path: /demo
      spring:
        datasource:
          url: jdbc:mysql://localhost:3306/test
          username: root
          password: admin123
          driver-class-name: com.mysql.jdbc.Driver

三、Java 配置方式

3.1 如何将一个类配置给Spring容器进行管理呢 ?

  • 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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    ​
        <bean id="user" class="com.qfedu.springboot.demo2.beans.User"></bean>
    ​
    </beans>
  • 注解配置

    @Component
    public class User {
      //...
    }
  • Java配置

    @Configuration
    public class SpringConfig {
    ​
        @Bean
        public Date getDate(){
            return new Date();
        }
        
    }

3.2 Spring版本发展

  • Spring 1.x

    • 所有bean的配置都必须在xml中完成

  • Spring 2.x

    • 基于JDK 1.5对注解的支持,Spring2.x开始使用注解配置

    • 企业开发中到时是使用xml还是注解呢 ?

      • 应用的基本配置用xml,比如:数据源、事务

      • 业务开发方面使用注解,比如:service、controller

  • Spring 3.x

    • 开始提供了基于Java的配置方式

  • Spring 4.x

    • Spring Boot 和Spring4.x 都提倡使用Java配置方式

四、Starter POM

Starter POM,指的是在pom文件中配置的SpringBoot提供的starter

  • 一个Starter我们就可以理解为对一种开发场景的支持

  • SpringBoot为我们提供了简化企业级开发绝大多数场景的支持(多个StarterPOM),在我们的项目中只要使用了对应场景的StarterPOM,相关的技术配置就会被内置进来(消除人工配置),同时我们就可以获得SpringBoot为我们提供的内置的Bean。

  • 案例: redis

    • 在pom.xml中引入redis对应的starter

      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-redis</artifactId>
      </dependency>
    • 在service中就可以直接使用SpringBoot内置的基于redis的开发场景(直接使用Bean)

      @Service
      public class RedisService {
      ​
          @Resource
          private RedisTemplate redisTemplate;
      ​
      }
  • SpringBoot支持绝大多数的主流框架(提供对应的starter),但并不是所有;支持的主流框架如下:

五、SpringBoot的自动配置

5.1 运行SpringBoot应用的启动类

@SpringBootApplication
public class SpringbootDemo2Application {
	public static void main(String[] args) {
		//SpringApplication.run 启动一个SpringBoot应用
		//run传递的class对象需要有 @SpringBootApplication 注解,
        //SpringBoot应用的加载是从@SpringBootApplication开始
		SpringApplication.run(SpringbootDemo2Application.class, args);
	}
}
  • @SpringBootApplication注解:是一个组合注解,包括配置、自动配置、扫描功能的启动

5.2 SpringApplication

public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
    // Class[] primarySources  ------------   SpringbootDemo2Application.class
    // 相当于SpringbootDemo2Application.class-->SpringApplication然后调用run方法
    return (new SpringApplication(primarySources)).run(args);
}

//相当于用SpringbootDemo2Application.class调用的此run方法,此run方法中的this就表示我们自己的应用
public ConfigurableApplicationContext run(String... args) {
	//...
    Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
    //...
    // 获取我们自己的应用程序的Spring对象工厂实例
    exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
    //...
}
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
    //...
    Set<String> names = new LinkedHashSet(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
    //...
}

5.3 SpringFactoriesLoader

public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
    String factoryTypeName = factoryType.getName();
    return (List)loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
}
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
	//...
    //加载Spring的自动配置文件:
    Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
	//...

}

5.4 spring.factories

  • 在此文件中列出了SpringBoot内置的所有配置(Java配置)

  • 在启动SpringBoot应用的时候,所有内置的自动配置类都会扫描;但并不是所有的配置都会被初始化,

# Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\
org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener

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

# Auto Configuration Import Listeners
org.springframework.boot.autoconfigure.AutoConfigurationImportListener=\
org.springframework.boot.autoconfigure.condition.ConditionEvaluationReportAutoConfigurationImportListener

# Auto Configuration Import Filters
org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\
org.springframework.boot.autoconfigure.condition.OnBeanCondition,\
org.springframework.boot.autoconfigure.condition.OnClassCondition,\
org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition

# 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.cloud.CloudServiceConnectorsAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
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.ElasticsearchAutoConfiguration,\
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.ReactiveRestClientAutoConfiguration,\
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.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.jest.JestAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.rest.RestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
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.groovy.template.GroovyTemplateAutoConfiguration,\
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.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.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

# Failure analyzers
org.springframework.boot.diagnostics.FailureAnalyzer=\
org.springframework.boot.autoconfigure.diagnostics.analyzer.NoSuchBeanDefinitionFailureAnalyzer,\
org.springframework.boot.autoconfigure.flyway.FlywayMigrationScriptMissingFailureAnalyzer,\
org.springframework.boot.autoconfigure.jdbc.DataSourceBeanCreationFailureAnalyzer,\
org.springframework.boot.autoconfigure.jdbc.HikariDriverConfigurationFailureAnalyzer,\
org.springframework.boot.autoconfigure.session.NonUniqueSessionRepositoryFailureAnalyzer

# Template availability providers
org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider=\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.mustache.MustacheTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.web.servlet.JspTemplateAvailabilityProvider

  • 自动配置类的条件注解

@ConditionalOnClass 表示的意思是:在当前类路径下存在某个类
@ConditionalOnMissingClass  表示的意思是:在当前类路径下不存在某个类
@EnableConfigurationProperties 表示的意思是:有相关的属性设置
@ConditionalOnBean 表示的意思是:当前IoC容器中存在某个bean
@ConditionalOnMissingBean 表示的意思是:当前IoC容器中不存在某个bean
@ConditionalOnJava 表示的意思是:需要满足指定的java虚拟机版本
@ConditionalOnResource 表示的意思是:在resources目录下存在指定的资源文件时才生效

六、SpringBoot常用注解

6.1 @SpringBootApplication

  • SpringBoot项目都有一个*Application类入口,入库类中是有main方法的,在此类添加@SpringBootApplication表示是当前应用的入口程序。

  • @SpringBootApplication是一个组合注解:

    • @SpringBootConfiguration

    • @EnableAutoConfiguration

    • @ComponentScan

6.2 @SpringBootConfiguration

  • 继承了@Configuration注解,并且作用一致,都是用来声明当前类为一个Java配置类。

6.3 @EnableAutoConfiguration

  • 启用SpringBoot内置的自动配置功能

6.4 @ComponentScan

  • 扫描bean,扫描范围是当前应用的入口程序所在的包

6.5 IoC注解

6.5.1 组件注册

  • @Component 普通组件注册

  • @Controller MVC控制层注解

  • @Service 业务逻辑层组件注册

  • @Repository 持久层组件组测

6.5.2 依赖注入注解

  • @Autowired / @Inject

  • @Qualifier

  • @Resource

6.5.3 作用域、声明周期

  • @Scope

  • @PostConstruct

  • @PreDestory

6.6 SpringMVC注解

  • @Controller

  • @RestController

  • @RequestMapping

  • @RequestBody

  • @ResponseBody

  • @PathVariable

七、日志管理

  • SpringBoot提供了log4j、logback等日志框架的支持

  • 默认情况下,使用的logback进行日志管理

  • 我们只需要指定日志文件或者指定日志文件的存储目录即可:

    • 指定日志文件名称,表示日志存储在当前工作空间下的logs目录中20200417.log文件

      logging:
        file: logs/20200417.log
      -----------------------------------
      logging:
        file: 
          name: logs/20200417.log
      
    • 指定日志文件存储的目录,表示日志存储在当前工作空间下的logs目录中的20200417目录中

      logging:
        file:
          path: logs/2020417
      

猜你喜欢

转载自blog.csdn.net/u014748504/article/details/108490791