Springboot 学习笔记

一、springboot 入门

1、 Spring boot 简介

2、 微服务

谷粒学院 学习idea

3、 环境准备

jdk1.8

maven 3.3以上

idea2017

SpringBoot 1.5.9

maven设置

给maven的settings.xml文件标签添加

​ profile jdk1.8

IDea设置 build > maven 设置自己的maven 和setting文件

4、Spring hello world

1、 创建一个maven工程(jar)

2、 导入依赖Springboot相关的依赖

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
 <!--可以将应用打包成一个可执行的jar包-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

5、hello 探究

1、POM文件

1.父项目

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>
    
 他的父项目是
 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath>../../spring-boot-dependencies</relativePath>
</parent>
 
 他来真正管理Springboot应用里面的所有依赖版本:

Spring Boot的版本仲裁中心:

以后导入依赖默认是不需要写版本。(没有在dependencies中管理的依赖自然需要声明版本号)

2. 导入的依赖

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

spring-boot-srarter-web

​ springboot场景启动器:导入了web模块正常运行所依赖的组件;

Spring Boot将所有的功能场景都抽取出来,做成一个个的starters(启动器),只需要在项目中引入这些starter相关场景的所有依赖都会导入进来,要用什么功能,就导入什么场景启动器。

2、主程序类,主入口类

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

@SpringBootApplication : Spring Boot 应用标注在某个类上,说明这个类是SpringBoot的主配置类,SpringBoot就应该运行这个类的main方法来启动SpringBoot应用。

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

@SpringBootConfiguration : SpringBoot的配置类;

​ 标注在某个类上,表示这是一个SpringBoot的配置类;

​ @Configuration:配置类上来标注这个注解;

​ 配置类------配置文件;配置类也是容器中的一个组件:@component

@EnableAutoConfiguration:开启自动配置功能;

​ 以前需要配置的东西,现在SpringBoot帮我们自动配置。

@AutoConfigurationPackage
@Import({EnableAutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {

@AutoConfigurationPackage:自动配置包

​ @Import({Registrar.class})

​ Spring的底层注解@Import,给容器中导入一个组件,导入的组件由Registrar.class

​ 将主配置类(@SpringBootApplication标注的类)下面的包及下面所有组件扫描到Spring容器;

@Import({EnableAutoConfigurationImportSelector.class})

​ 给容器中导入组件?

​ EnableAutoConfigurationImportSelector:导入那些组件的选择器:

​ 将所有需要导入的组件以全类名的方式返回,这些组件就会被添加到容器中;

​ 会给容器中导入非常多的自动配置类(xxxAutoConfiguration);就是给容器中导入这个场景需要的所有组件,并配置好这些组件;

有了自动配置类,免去手动编写配置注入功能组件等工作;

SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class,classLoader)

从类路径下得META_INF/spring.factories中获取EnableAutoConfiguration制定的值,将这些值作为自动配置陪导入到容器中,自动配置类就生效,帮我们进行自动配置工作。

6、 快速创建SpringBoot

  • 默认生成的SpringBoot项目:
  • 主程序已经生成好,只需要编辑自己的逻辑
  • resources文件夹中的目录结构
    • static:保存所有的静态资源;js css images;
    • templates: 保存所有的模板页面;(默认jar包,嵌入式tomcat,默认不支持jsp页面),可以使用模板引擎(freemarker,thymeleaf);
    • application.properties:SpringBoot应用的配置文件。可以修改一些默认设置。

二、配置文件

1、 配置文件properties比yml优先级高

SpringBoot使用一个全句的配置文件,配置文件名是固定的;

application.properties

application.yml

配置文件的作用:修改SpringBoot自动配置的默认值,SpringBoot在底层都给我们自动配置好了。

YAML, 是/不是一个标记语言

标记语言:

​ 以前的配置文件:xxx.xml

​ yaml:以数据为中心,比json、xml等更适合做配置文件。

2、YAML语法:

1.基本语法

​ k: 空格V:表示一对键值对(空格必须有):

​ 以空格的缩进来控制层级关系

server:
  port: 8095
  path: /hello

属性和值也是大小写敏感;

2.值的写法

字面量:普通的值(数字、字符串,布尔)

​ k: v: 字面直接来写;

​ 字符串默认不用加上单引号或者双引号;

​ '':会转义特殊字符,特殊字符会被转为一个普通的字符串输出

​ name: "zhangsan n lisi"

​ 输出:zhangsan n lisi

​ "":不会转义字符串里面的特殊字符,特殊字符会作为本身想表示的意思

​ name: "zhangsan n lisi"

​ 输出:zhangsan

​ lisi

对象(属性和值)(键值对):

​ k: v :在下一行来写对象的属性和值的关系,注意缩进

​ 对象还是k: v的方式

friends:
    lastName: zhangsan
    age: 20

数组(list、set):

用-值表示数组中的一个元素

pets:
    - cat
    - dog
    - pig
pets: [cat,dog,pig] 

3.配置文件值注入

配置文件yml

person:
  lastName: zhangsan
  age: 18
  boss: false
  birth: 2018/10/10
  maps: {
          k1: v1,
          k2: 12,
          k3: 20
  }
  lists:
    - lisi
    - wangwu
  dog:
    name: 小狗
    age: 2

javaBean:

/**
*通过@ConfigurationProperties(prefix = "person")注入
*/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String lastName;
    private Integer age;
    private Boolean boos;
    private Date birth;

    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

我们可以导入pom.xml配置文件处理器,这样编写yml就会有提示

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
@Value("${person.last-name}")
private String lastName;
@Value("#{11*2}")
private Integer age;
@Value("true")
private Boolean boos;

1.idea中yml配置文件默认utf-8有可能乱码

2.@value获取值与@configurationProperties获取值比较

@configurationProperties @value
功能 批量注入配置文件中的属性 一个个指定
松散绑定 支持 不支持
SpEL 不支持 支持(#/${}...)
JSR303数据校验 支持 不支持
支持 不支持

配置文件yml还是properties他们都能获取到值。

如果说,我们只是在某个业务逻辑中,需要获取一下配置文件中的某项值,我们使用@value

如果为list或map或专门编写了一个javaBean来和配置文件进行映射,使用@ConfigurationProperties。

3.配置文件注入值数据校验

@ConfigurationProperties(prefix = "person")
@Validated

4.@PropertySource与ImportResource

/**
 * 将配置文件中配置的每一个属性的值,映射到这个组件中
 * @ConfigurationProperties: 告诉springboot将奔雷中的所有属性和配置文件中的相关的配置进行绑定
 *      prefix = "persion" : 配置文件中哪个下面的所有属性进行一一映射
 * 只有这个组件是容器中的组件,才能使用容器提供的ConfigurationProperties功能
 * @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值;
 */
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
//    @Value("${person.last-name}")
    private String lastName;
//    @Value("#{11*2}")
    private Integer age;
//    @Value("true")
    private Boolean boos;
    private Date birth;

    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

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

SpringBoot里面没有Spirng的配置文件,我们自己编写的配置文件,也不能自动识别;

想让Spring的配置文件生效,加载进来@importResource,标注在一个配置类上

@ImportResource(locations = {"classpath: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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="helloService" class="com.better.springhelloword.service.HelloService"></bean>
</beans>

SpringBoot推荐给容器中添加组件的方式:

1.配置类===Spring配置文件

2.使用@Bean给容器中添加组件

/**
 *@Configuration:指明当前类是一个配置类,就是来替代之前的Spring配置文件
 * 在配置文件中用<bean><bean/> 标签添加组件
 */
@Configuration
public class MyAppConfig {
    //将方法的返回值添加到容器中
    @Bean
    public HelloService helloService(){
        System.out.println("配置类:");
        return new HelloService();
    }
}

4、配置文件占位符

1.随机数

person.last-name=李四${random.uuid}
person.age=${random.int}

2.占位符获取之前的配置的值,如果没有可以用:指定默认值

person.dog.name=${person.last-name}_dog

person.dog.name=${person.hello:hello}_dog

5、Profile

1、多Profile文件

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

2、yml支持多文档块方式

server:
  port: 8095
spring:
  profiles:
    active: prod
---
server:
  port: 8080
spring:
  profiles: dev
---
server:
     port: 8081
spring:
  profiles: prod

3、激活指定profile

创建application-dev.properties

1.在配置文件(application.properties)中指定spring.profiles.active=dev

2.命令行参数:program arguments:

​ --spring.profiles.active=dev

​ 运行jar包

​ java -jar spring-boot-02-config-0.1.1.jar --spring.profiles.active=dev

3.虚拟机参数 VM options:

​ -Dspring.profiles.active=dev

6、配置文件加载位置(高>低)

-file:../config/

-file:../

-classpath:../config/

-classpath:../

高优先级的配置会覆盖低优先级的配置。(所有配置文件都会加载,会形成互补机制)

我们还可以通过spring.config.location来改变默认的配置文件位置

项目打包好之后,我们可以使用命令行参数的形式,启动项目的时候来指定配置文件的新位置;指定配置文件和默认加载的这些配置文件共同起作用形成互补配置;

7、外部配置加载顺序

SpringBoot也可以从以下位置加载配置;优先级从高到低,高优先级的配置覆盖低优先级的配置,所有的配置会形成互补配置。

java -jar spring.jar --参数 --参数...

多个参数可以用空格分开

由jar包外向jar包内进行寻找;优先加载带profile,再来加载不带profile的。

8、自动配置原理

配置文件到底能写什么?怎么写?自动配置原理;

springboot官方文档

1、自动配置原理;

​ 1) SpringBoot启动的时候加载主配置类,开启了自动配置功能==@EnableAutoConfiguration==

​ 2) @EnableAutoConfiguration作用:

​ 利用AutoConfigurationImportSelector给容器中导入了一些组件

​ 可以查看selectImports()方法的内容;

==参照5.3 快速创建SpringBoot中的自动配置==

有了自动配置类,免去手动编写配置注入功能组件等工作;

SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class,classLoader)

从类路径下得META_INF/spring.factories中获取EnableAutoConfiguration制定的值,将这些值作为自动配置陪导入到容器中,自动配置类就生效,帮我们进行自动配置工作。

# 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.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.reactor.core.ReactorCoreAutoConfiguration,
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,
org.springframework.boot.autoconfigure.security.servlet.SecurityRequestMatcherProviderAutoConfiguration,
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.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)每一个自动配置了进行自动配置功能

4)以HttpEncodingAutoConfiguration为例解释自动配置原理。

@Configuration //表示这是一个配置类,以前编写的配置文件一样,也可以给容器中添加组件
@EnableConfigurationProperties(HttpProperties.class)  //启动ConfigurationProperties功能,将配置文件中对应的值和HtppEncodingProperties绑定起来;
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)//Spring底层的注解,根据不同的标间,如果满足指定的条件,整个配置类里面的配置就会生效 判断是否web应用,是就生效
@ConditionalOnClass(CharacterEncodingFilter.class)//判断当前项目有没有这个类,CharacterEncodingFilter:SpringMVC中进行乱码解决的过滤器
@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)//判断配置文件中是或否存在某个配置,spring.http.encoding.enabled,如果不存在判断也是成立的
public class HttpEncodingAutoConfiguration {
    //只有一个有残构造器的情况下,参数的值就会从容器中拿
    public HttpEncodingAutoConfiguration(HttpProperties properties) {
        this.properties = properties.getEncoding();
    }

    
    @Bean //给容器中添加一个组件,这个组件的某些值从properties中获取
    @ConditionalOnMissingBean
    public CharacterEncodingFilter characterEncodingFilter() {
        CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
        filter.setEncoding(this.properties.getCharset().name());
        filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));
        filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));
        return filter;
    }

根据当前不同的条件判断,决定这个配置类是否生效

一旦这个配置类生效,这个属性类就会给容器中添加各种组件,这些组件的属性是从对饮的properties类中获取的,这些类里面的每个属性又是和配置类绑定的,

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

@ConfigurationProperties(prefix = "spring.http") //从配置文件中获取指定的值和bean的属性进行绑定
public class HttpProperties {

2、细节

1. @conditional派生注解(Spring注解版原生的@conditional作用)

作用:必须是@conditional指定的条件成立,才给容器中添加组件,配置类里面的所有内容才生效。

自动配置类必须在一定的条件下才能生效。

如何查看生效的配置类:

我们可以通过启用debug=true属性,来让控制台答应自动配置报告,这样我们就可以很方便的知道哪些自动配置类生效。

Positive matches: 自动配置类启用的自动配置类

Negative matches:自动配置类未启用的自动配置类

21日志

四、SpringBoot与web开发

1、使用SpringBoot:

1)创建SpringBoot应用,选中我们需要的模块;

2)SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置,就可以运行起来

3) 自己编写业务代码

自动配置原理?

这个场景SpringBoot帮我们配置了什么?能不能修改?能修改哪些配置,能不能扩展?

xxxAutoConfiguration:帮我们给容器中自动配置组件
xxxProperties:配置类来封装配置文件的内容 

2、SpringBoot对静态资源的映射规则

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {
// 可以设置和静态资源有关的参数,缓存时间等
    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/resources/",
            "classpath:/static/", "classpath:/public/" };
    
@Override//映射所有静态资源
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
                return;
            }
            Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
            CacheControl cacheControl = this.resourceProperties.getCache()
                    .getCachecontrol().toHttpCacheControl();
            if (!registry.hasMappingForPattern("/webjars/**")) {
                customizeResourceHandlerRegistration(registry
                        .addResourceHandler("/webjars/**")
                        .addResourceLocations("classpath:/META-INF/resources/webjars/")
                        .setCachePeriod(getSeconds(cachePeriod))
                        .setCacheControl(cacheControl));
            }
            String staticPathPattern = this.mvcProperties.getStaticPathPattern();
            if (!registry.hasMappingForPattern(staticPathPattern)) {
                customizeResourceHandlerRegistration(
                        registry.addResourceHandler(staticPathPattern)
                                .addResourceLocations(getResourceLocations(
                                        this.resourceProperties.getStaticLocations()))
                                .setCachePeriod(getSeconds(cachePeriod))
                                .setCacheControl(cacheControl));
            }
        }
        //映射所有图标路径 "**/favicon.ico"
        @Bean
            public SimpleUrlHandlerMapping faviconHandlerMapping() {
                SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
                mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
                mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",
                        faviconRequestHandler()));
                return mapping;
            }

//映射欢迎首页
    @Bean
        public WelcomePageHandlerMapping welcomePageHandlerMapping(
                ApplicationContext applicationContext) {
            return new WelcomePageHandlerMapping(
                    new TemplateAvailabilityProviders(applicationContext),
                    applicationContext, getWelcomePage(),
                    this.mvcProperties.getStaticPathPattern());
        }

1) 所有/webjars/都去classpath:/META-INF/resources/webjars/找资源;

webjars:以jar包的方式引入静态资源;

2) “/”访问当前项目的任何资源(静态资源的文件夹)

"classpath:/META-INF/resources/", 
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/" 
"/" 当前项目的根路径

如果自定义了,默认的路径就失效

localhost:8080/abc 去类路径下找abc

http://localhost:8005/static/admin/css/page.css

3) 欢迎页;静态资源文件夹下得所有index.html页面,被“/”映射;

localhost:8080 / 找资源下的index页面

4)所有页面下“/favicon.ico” 都是在静态资源文件下找‘

3、模板引擎

JSP、Velocity、Freemarker、Thymeleaf

Thymeleaf:语法更简单,功能更强大;

1) 引入Thymeleaf;

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

可以通过手动修改版本,

2)Thymeleaf使用&语法

public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");
    private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    
    //只要我们把Html页面放在classpaath:/templates/,thymeleaf就能自动渲染

//只要我们把Html页面放在classpaath:/templates/,thymeleaf就能自动渲染

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!