Spring Boot 学习(一)@SpringBootAppliction、配置文件、自动原理、SpringBoot单元测试、日志使用

一.@SpringBootAppliction

@SpringBootAppliction 标注一个主程序类,说明这个是个Spring Boot应用

@SpringBootApplication
public class MainApplication {

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

@SpringBootAppliction里面包含其他注解
下面讲@SpringBootConfiguration和@EnableAutoConfiguration

@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

Spring Boot的配置类 ,标注这是一个SpringBoot的配置类

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

1)包含@configuration 配置类

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

2.@EnableAutoConfiguration

开启自动配置功能

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

@EnableAutoConfiguration包含
@AutoConfigurationPackage和@import(EnableAutoConfigurationImportSelector.class)

1)其中@AutoConfigurationPackage 自动配置包

又包含@import(AutoConfigurationPackages.Registrar.class)。
@import是Spring的底层注解,给容器中导入一个组件,导入的组件由AutoConfigurationPackages.Registrar.class。 他的作用是会将主配置类(@SpringBootApplication标注的类)所在包及下面所有子包里面的所有组件扫描到Spring容器中

2)@import(EnableAutoConfigurationImportSelector.class)

给容器中导入组件

里面的参数EnableAutoConfigurationImportSelector.class 为了告诉要导入那些组件 ,将所有需要导入的组件以全类名的方式返回, 这些会被添加到容器中

二.配置文件

(1)yml(YAML Ain’t Markup Language)

yml 以数据为中心,比json,xml更加适合做配置文件

1.配置文件

SpringBoot使用一个全局配置文件,固定名字application.properties或者application.yml

2.对比

yml

server:
 port: 8081

xml

<server>
  <port>8081</port>
</server>

3.yml语法

基本语法:
k:(空格)v 表示一对键值对(空格必须有)
以空格的缩进进行控制层级关系;只要是左对齐的一列数据,都是同一级别
属性和值是大小写敏感的
yml

server:
  port: 8081
  path: /hello

值的写法:
字面量:普通的值(数字,字符串,布尔)
字面量可以直接写,字符串不用加引号
""双引号:不会转义字符串里面的特殊字符,如’\n’输出就是换行
‘’单引号:会转义,当作普通文本输出 ,如‘\n’输出就是’\n’

对象,Map(属性和值)(键值对)
对象写法一:

student:
  name: zhangsan
  age: 18

对象写法二:行内写法

student: { name: zhangsan,age: 18}

数组(List,Set)
用-(空格)值表示数组中的一个元素

pets:
 - cat
 - dog
 - pig

行内写法:

pets: [cat,dog,pig]

数据绑定

类上加@ConfigurationProperties(prefix = “person”)
prefix 是指定配置文件中的哪个属性进行绑定
@Component表示添加进容器,只有先进了容器才能使用容器的方法

@Component
@ConfigurationProperties(prefix = "ptes")
public class Ptes{
}

使用@ConfigurationProperties还需在maven中导入包
引入jar之后,在application.yml中给自定义对象属性初始化值的时候会有属性名的提示

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

(2)properties

#配置person的值
person.age=18
person.birth=2017/12/15
person.boss=false
person.maps.k1=aa
person.maps.k2=13
person.lists=a,b,c
person.dog.name=zs
person.dog.age=5

(3)@Value和@ConfigurationProperties为属性注入值的对比

默认是从全局配置文件中取值

对比@ConfigurationProperties@Value
功能支持批量注入配置文件中的属性一个个注入
松散绑定(松散语法)支持不支持
SpEL不支持支持
JSE303数据校验支持不支持
复杂类型封装支持不支持

JSE303数据校验:

@Email
private String email; 

怎么选择?
1.只在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value
2.专门写了一个javaBean来和配置文件进行配置 ,选择@ConfigurationProperties

(4)@PropertySource

当不使用全局配置文件,自己指定一个文件时:

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

(5)@importResource

@importResource:导入Spring配置文件,让配置文件里面的内容生效

在配置类上面添加自定义的配置文件

@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class MainApplication {

(6)@bean

Springboot推荐给容器添加组件的方式;推荐使用全注解的方式;
1.配置类configuration -->Spring配置文件
2.使用@bean给容器中添加组件

@Configuration //指明当前类为配置类
public class MyConfig {

    //将方法的返回值添加到容器中,容器中这个组件默认的id就是方法名
    @Bean
    public HelloService helloService(){

        return new HelloService();
    }
}

(7)配置文件占位符

 #可以拼接一些随机数
person.name=张三{$random.int} 

 #可以引用前面配置过的属性,:后面是默认值;
 #没找到对应的值的时候,使用默认值。
person.age=13{$person.name:李四}

(8)Profile多环境支持

1.多Profile文件
我们在配置文件编写的时候,文件名字可以是application-{profile}.properties/yml

2.yml支持多文档块方式

3.激活指定profile
第一种(properties):在配置文件中指定spring.profiles.active=xxx

第二种(yml):可以在一个文件中

第三种(命名行):java -jar xxx.jar --spring.profiles.active=dev;
第四种(虚拟机):-Dspring.profiles.active=dev

(9)配置文件加载位置

Springboot启动会扫描以下位置的application.properties/yml作为springboot的默认配置文件:
file:./config/
file:./
classpath:/config/
classpath:/
优先级从高到底,优先级高的会覆盖优先级低的的相同配置,不相同的配置会全部加载,互补。

(10)外部配置加载顺序

springboot也可以从以下位置加载配置;优先级从高到低
1.命名行参数
2.来自java:comp/env的JNDI属性
3.java系统属性(System.getProperties())
4.操作系统环境变量
5.RandomValuePropertySource配置的random.*属性值
6.jar包外部的application-{profile}.properties/yml(带spring.profiles)
7.jar包内部的application-{profile}.properties/yml(带spring.profiles)
8.jar包外部的application-{profile}.properties/yml(不带spring.profiles)
9.jar包内部的application-{profile}.properties/yml(不带spring.profiles)
10.@Configuration注解类上的@PropertySource
11.通过SpringApplication.setDefaultProperties指定的默认属性

server:
  port: 8080
spring:
  profiles:
    active: dev

---
server:
  port: 8081
spring:
  profiles: dev

---
server:
  port: 8082
spring:
  profiles: prod

(11)自动原理

1.springboot启动时加载主配置类,开启了自动配合功能
@EnableAutoConfiguration

@SpringBootApplication
public class MainApplication {

进到@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 {

2.@EnableAutoConfiguration作用:利用EnableAutoConfigurationImportSelector给容器中导入一些组件。
查看父类AutoConfigurationImportSelector中的selectImports方法

上面是老版本;
新版直接访问AutoConfigurationImportSelector

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

进到EnableAutoConfiguration 后,查看selectImports方法,可以得知导入了哪些组件

    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        if (!this.isEnabled(annotationMetadata)) {
            return NO_IMPORTS;
        } else {
            AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
            //进入getAutoConfigurationEntry方法
            AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata);
            return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
        }
    }

//进入getAutoConfigurationEntry方法


    protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata, AnnotationMetadata annotationMetadata) {
        if (!this.isEnabled(annotationMetadata)) {
            return EMPTY_ENTRY;
        } else {
            AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
            //获取候选的配置; 
            List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
            configurations = this.removeDuplicates(configurations);
            Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
            this.checkExcludedClasses(configurations, exclusions);
            configurations.removeAll(exclusions);
            configurations = this.filter(configurations, autoConfigurationMetadata);
            this.fireAutoConfigurationImportEvents(configurations, exclusions);
            return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);
        }
    }

进入getCandidateConfigurations

    protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
    //1.进入loadFactoryNames  
    //2.进入getSpringFactoriesLoaderFactoryClass
        List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
        Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
        return configurations;
    }

1.进入loadFactoryNames

  public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
       //从传进来的factoryType获得factoryTypeName
       //factoryType的值可以从下面2.getSpringFactoriesLoaderFactoryClass中获得
        String factoryTypeName = factoryType.getName();
        //进入loadSpringFactories
        return (List)loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
    }

查看 2.getSpringFactoriesLoaderFactoryClass里面,发现加载的是EnableAutoConfiguration

   protected Class<?> getSpringFactoriesLoaderFactoryClass() {
        return EnableAutoConfiguration.class;
    }

进入loadSpringFactories
loadSpringFactories的作用:
1.扫描所有jar包路径下META-INF/spring.factories
2.把所有扫描到的文件的内容包装成properties对象

  private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
        MultiValueMap<String, String> result = (MultiValueMap)cache.get(classLoader);
        if (result != null) {
            return result;
        } else {
            try {
            //扫描所有jar包路径下META-INF/spring.factories
                Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
                LinkedMultiValueMap result = new LinkedMultiValueMap();
              //把所有扫描到的文件的内容包装成properties对象
                while(urls.hasMoreElements()) {
                    URL url = (URL)urls.nextElement();
                    UrlResource resource = new UrlResource(url);
                    Properties properties = PropertiesLoaderUtils.loadProperties(resource);    
                      //从properties中获取EnableAutoConfigurationd的值加入到容器中(哪些值?下面讲解)         
                    Iterator var6 = properties.entrySet().iterator();
                    while(var6.hasNext()) {
                        Entry<?, ?> entry = (Entry)var6.next();
                        String factoryTypeName = ((String)entry.getKey()).trim();
                        String[] var9 = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
                        int var10 = var9.length;

                        for(int var11 = 0; var11 < var10; ++var11) {
                            String factoryImplementationName = var9[var11];
                            result.add(factoryTypeName, factoryImplementationName.trim());
                        }
                    }
                }

                cache.put(classLoader, result);
                return result;
            } catch (IOException var13) {
                throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var13);
            }
        }
    }

哪些值?将类路径下META-INF/spring.factories里面配置的所有EnableAutoConfigurationd的值加入容器
每一个xxxAutoConfiguration类都是容器中的一个组件,都加入到容器中;用他们做配置;
每一个自动配置类,进行自动配置功能

# 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

以HttpEncodingAutoConfiguration来讲解自动配置原理

//表示这是一个配置类
@Configuration( 
    proxyBeanMethods = false
)
//启动指定类的@ConfigurationProperties;将配置文件中对应的值和@EnableConfigurationProperties绑定
@EnableConfigurationProperties({HttpProperties.class}) 

//spring底层@Conditional注解(Spring注解版),根据不同的条件,如果满足指定的条件,整个配置类里面的配置会生效; 判断当前是否是web应用,如果是,当前配置就生效
@ConditionalOnWebApplication(
    type = Type.SERVLET
)
//判断当前项目中是否有CharacterEncodingFilter
//CharacterEncodingFilter : springMVC中进行解决乱码问题
@ConditionalOnClass({CharacterEncodingFilter.class})

//判断配置文件中是否存在spring.http.encoding.enabled;
//如果不存在,判断也是成立的,默认spring.http.encoding.enabled=true( matchIfMissing = true)
@ConditionalOnProperty(
    prefix = "spring.http.encoding",
    value = {"enabled"},
    matchIfMissing = true
)
public class HttpEncodingAutoConfiguration {
    
    //映射后的properties
    private final Encoding properties;

    //只要一个有参构造器的情况下,参数就会从容器中获取
    public HttpEncodingAutoConfiguration(HttpProperties properties) {
        this.properties = properties.getEncoding();
    }

    @Bean 
    @ConditionalOnMissingBean
    public CharacterEncodingFilter characterEncodingFilter() {
        CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
        filter.setEncoding(this.properties.getCharset().name());
        filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.REQUEST));
        filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.RESPONSE));
        return filter;
    }

所有在配置类中能配置的属性都是在xxxProperties类中封装着,配置文件能配置什么就可以参照某个功能对应的这个属性类。

@ConfigurationProperties(
    prefix = "spring.http"
)
public class HttpProperties {
    private boolean logRequestDetails;
    private final HttpProperties.Encoding encoding = new HttpProperties.Encoding();

总结
1.springboot启动会加载大量的自动配置类
2.我们看我们需要的功能有没有Springboot默认写好的自动配置类
3.我们再来看这个自动配置类中到底配置了哪些组件(如果我们要用的组件自动配置了,我们就不用再配了)
4.给容器中自动配置类添加组件的时候,会从properties类中获取属性。我们就可以在配置文件中取出这些属性值。

自动配置报告

在配置文件中添加debug=true 开启debug模式,启动的时候,控制台就会打印自动配置的类和没自动配置的类

四.SpringBoot单元测试

在test文件夹中

//可以在测试期间使用自动注入
@RunWith(SpringRunner.class)//单元测试使用SpringBoot的驱动器
@SpringBootTest
public class SprigBoot02ConfigApplicationTests{
   @Autowired
   Person person;

    @Test
    public void contextLoads(){
    System.out.println(person);
    }
}

五.日志

基本介绍

1.springboot底层使用slf4j+logback的方式进行日志记录
2.springboot也把其他日志文件都替换成slf4j(会用中间的转换包)
3.springboot能自动配置所有的日志,在导入其他框架的时候,只需把这个框架的日志包排除即可。

日志级别

    //日志记录器
    Logger logger = LoggerFactory.getLogger(getClass());
    @RequestMapping("/hello")
    public String hello(){

        //日志级别,默认info,也就是输出(info,warn,error)
        //由高到低 trance <debug <info <warn <error  
        logger.trace("这个trace 跟踪轨迹");
        logger.debug("这个debug 调试信息");
        logger.info("这个info 自定义信息");
        logger.warn("这个warn 警告");
        logger.error("这个error 错误");


        return "login_admin";
    }

日志使用

配置文件中
loggin.leve.路径 可以设置路径下的日志级别

login.fileloggin.path说明
(none)(none)只在控制台输出
指定文件名(none)当前项目下输出日志到 xx文件中(也可以写路径)
(none)指定目录输出日志到指定目录的 xx文件中

同时指定login.file ,loggin.path 的时候,只有login.file起作用。

loggin.level.com.pt=trace
login.file=springboot.log
#当前磁盘的根路径下创建spring文件夹和里面的log文件夹;使用spring.log作为默认文件
loggin.path=/spring/log

日志的输出格式:

%d 表示日期时间 如%d{yyyy-MM-dd HH:mm:ss.SSS}
%thread 表示线程名
%-5level 级别从左显示5个字符宽度
%logger{50} 表示logger名字最长字符,否则按照句点分割
%msg 日志消息
%n 换行符

配置文件中设置输出格式

#控制台日志输出格式 logging.pattern.console=
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread]  %-5level %logger{50}  %msg%n

#文件日志输出格式 logging.pattern.file=
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread]  %-5level %logger{50}  %msg%n

指定日志和profile功能
使用logback-spring.xml 日志框架就不能直接加载日志的配置项了,由springboot解析日志配置,可以使用springboot的高级profile功能

<springProfile name="dev">
   <!--......指定dev环境下的内容-->
</springProfile >

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值