( excludeFilters = { ( type = FilterType.CUSTOM, classes = {TypeExcludeFilter.class} ), ( type = FilterType.CUSTOM, classes = {AutoConfigurationExcludeFilter.class} )} ) public @interface SpringBootApplication {
@SpringBootConfiguration:Springboot的配置类
标注在这个类上表示这是一个springboot配置类
@Configuration:配置类上来标注这个注解
配置类--配置文件:配置类也是容器的一个组件:@Component
@EnableAutoConfiguration:开启自动配置功能
EnableAutoConfigurationImportSelector.class}) ({public @interface EnableAutoConfiguration {
@AutoConfigurationPackage:自动配置包
@Import({Registrar.class})
Springboot的底层注解:给容器中导入一个组件;导入的组件由Registrar.class
将主配置类(@SpringBootApplication标注的类)的所在包及下面所有子包里面的所有组件扫描到Spring容器
@Import({EnableAutoConfigurationImportSelector.class}):给容器导入组件
EnableAutoConfigurationImportSelector:导入组件选择器
将所有需要导入的组件以全类名的方式返回;这些组件就会被添加到容器中
会给容器中导入非常多的自动配置类(XXXAutoConfiguration):就是给容器中导入这个场景所需要的所有组件,并配置好这些组件
有了自动配置类,就免去了手动编写配置注入功能组件等工作
SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
SpringBoot在启动时,从类路径下META-INF/spring.factories中获取 EnableAutoConfiguration指定的值; 将这些值作为自动配置类导入到容器中,自动配置类就生效,帮我们进行自动配置工作
J2EE的整体整合解决方案和自动配置都在spring-boot-autoconfigure-1.5.9.RELEASE.jar;
二、配置文件
yml文件是YAML语言文件,以数据为中心,比json、xml更适合做配置文件
值的写法
字面量:普通的值(数字、字符串、布尔)
k: v:字面直接来写;
"":双引号:name: "zhangsan \n lisi" 输出:zhangsan 回车 lisi
'':单引号:name:'zhangsan \n lisi ' 输出:zhangsan \n lisi
对象、Map(属性和值)(键值对):
k: v:在下一行来写对象的属性和值的关系
对象还是k: v的方式
friends lastName zhangsan age20
行内写法:
friends lastName zhangsanage18
数组(List、Set):
用-值表示数组中的一个元素
pets cat dog pig
行内写法
pets cat dog pig
3、配置文件值注入
配置文件
person lastName hello age18 bossfalse birth 2017/12/12 maps k1 v1k2 v2 lists lisi zhaoliu dog name:小狗 age:2
javaBean
prefix = "person") //ConfigurationProperties默认从全局配置文件中获取值 (public class Person { private String lastName; private Integer age; private Boolean boss; private Date birth; private Map<String,Object> maps; private List<Object> lists; private Dog dog; }
可以导入配置文件处理器,配置文件进行绑定会有提示
<!--导入配置文件处理器,配置文件进行绑定就会有提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
自动注入bean的另一种方法
public class Person { "${person.lastName}") ( private String lastName; "#{11*2}") ( private Integer age; "true") ( private Boolean boss; }
2、@Value获取值和ConfigurationProperties获取值的比较
@ConfigurationProperties | @Value | |
---|---|---|
功能 | 批量注入 | 单独制定 |
松散绑定(松散语法绑定) | 支持 | 不支持 |
SpEL | 不支持 | 支持 |
JSR303数据校验(@Validated) | 支持 | 不支持 |
复杂类型封装(例:map) | 支持 | 不支持 |
配置文件yml还是properties他们都能获取到值
如果只在某个业务逻辑中获取配置文件中的某项值,使用@Value
如果专门编写一个javaBean来和配置文件映射,使用@ConfigurationProperties
4、@PropertySource&@ImportResource
@PropertySource:加载指定的配置文件
eg: value = {"classpath:person.properties"}) ( prefix = "person") (public class Person{...}
@ImportResource:导入Spring的配置文件,让配置文件里面的内容生效;
Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件也不能自动识别;
如果想让spring配置文件生效,@ImportResource标注在一个配置类上
locations = {"classpath:beans.xml"}) ( public class SpringBootConfigApplication{...} 导入Spring的配置文件让其生效
SpringBoot推荐给容器中添加组件的方式:
1、配置类====spring配置文件
2、使用@Bean给容器中添加组件
/** * @Configuration:指明当前类是一个配置类,就是来代替之前的Spring配置文件 */ public class MyConfig{ //将方法的返回值添加到容器中,容器中这个组件的id就是方法名 public HelloService helloService() { return new HelloService; } }
四、配置文件占位符
1、随机数
${random.value}、${random.int}、${random.long}、${random.int(10)}、${random.int[1024,65536]}
2、占位符获取之前配置的值,如果没有可以是用:指定默认值
person.last-name=张三${random.uuid} person.age=${random.int} person.dog.name=${person.hello:hello}_dog //,冒号后面是默认值,如果没有指定默认值则显示${person.hello}
五、Profile
1、多Profile文件
我们在主配置文件编写时,文件名可以是application-dev.properties/yml
默认使用application.properties的配置;
2、yml支持多文档块方式
server port8081 spring profiles active:prod //此处可以快速切换指定的文档快配置 --- server port8083 spring profiles:dev --- server port:8084 spring profiles:prod
3、激活指定profile
1、在配置文件中指定spring.profiles.active=dev
2、命令行 java -jar spring-boot.jar --spring.profiles.active=dev 可以在测试的时候配置传入命令行参数
3、虚拟机参数:
VM options: -Dspring-profiles-active=dev
六、配置文件加载位置
springboot启动会扫描application.properties/yml文件作为默认配置文件
根目录/config > 根目录 > classpath:/config > classpath:根目录
SpringBoot会从这四个位置全部加载主配置文件:互补配置
也可以通过spring.config.location更改默认配置文件
java -jar spring-boot.jar --spring.config.location
项目打包好以后,使用命令行,启动项目制定配置文件的新位置;制定配置文件和默认加载的配置文件共同起作用形成互补配置
七、外部配置加载顺序
SpringBoot也可以从以下位置加载配置;优先级从高到低;高优先级的配置覆盖低优先级的配置,所有的配置会形成互补配置
1、命令行参数
java -jar spring-boot.jar --server.port=8082 --server.context.path=/abc
2、来自java:comp/env的JNDI的属性
3、java系统属性(System.getProperties())
4、操作系统环境变量
5、RandomValuePropertySource配置的random.*属性值
由jar包外向jar包内寻找,优先加载带profile
6、jar包外部的application-(profile).properties或application.yml(带spring.profile)配置文件
7、jar包内部的application-(profile).properties或application.yml(带spring.profile)配置文件
再来加载不带profile
8、jar包外部的application.properties/yml(不带spring.profile)配置文件
9、jar包内部的application.properties/yml(不带spring.profile)配置文件
10、@Configuration注解类上的@PropertySource
11、通过SpringApplication.setDefaultProperties制定的默认属性
八、自动配置原理
1、自动配置原理
自动配置原理
1)SpringBoot启动的时候加载主配置类,开启了自动配置功能@EnableAutoConfiguration
2)@EnableAutoConfiguration作用:
- 利用EnableAutoConfigurationImportSelector给容器中导入了一些组件 - 可以查看selectImports()方法的内容: - List<String> configuration = getCandidateConfigurations(annotationMetadata,attributes)获取候选的配置
SpringFactoriesLoader.loadFactoryNames(); 扫描所有jar包类路径下META-INF/spring.factories 把扫描到的这些文件的内容包装成properties对象 从properties中获取EnableAutoConfiguration.class类(类名)对应的值,然后把他们添加在容器中
将类路径下META-INF/spring.factories里面配置的所有EnableAutoConfiguration的值加入到了容器中;
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.CloudAutoConfiguration,\ 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.CassandraRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\ 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.jpa.JpaRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\ 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.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.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.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.flyway.FlywayAutoConfiguration,\ org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\ org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\ org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\ 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.mobile.DeviceResolverAutoConfiguration,\ org.springframework.boot.autoconfigure.mobile.DeviceDelegatingViewResolverAutoConfiguration,\ org.springframework.boot.autoconfigure.mobile.SitePreferenceAutoConfiguration,\ org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\ org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\ org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\ org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\ org.springframework.boot.autoconfigure.reactor.ReactorAutoConfiguration,\ org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration,\ org.springframework.boot.autoconfigure.security.SecurityFilterAutoConfiguration,\ org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration,\ org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration,\ org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\ org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\ org.springframework.boot.autoconfigure.social.SocialWebAutoConfiguration,\ org.springframework.boot.autoconfigure.social.FacebookAutoConfiguration,\ org.springframework.boot.autoconfigure.social.LinkedInAutoConfiguration,\ org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration,\ org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\ 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.DispatcherServletAutoConfiguration,\ org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration,\ org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration,\ org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration,\ org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration,\ org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration,\ org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration,\ org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration,\ org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration,\ org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration,\ org.springframework.boot.autoconfigure.websocket.WebSocketMessagingAutoConfiguration,\ org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration
每一个AutoConfiguration类都是容器中的一个组件,都加入到容器中;用他们来做自动配置
3)每一个自动配置类进行自动配置功能
4)以HttpEncodingAutoConfiguration(Http编码自动配置)为例解释自动配置原理:
//表示这是一个配置类,也可以给容器中添加组件 HttpEncodingProperties.class}) //启用指定类的ConfigurationProperties功能;将配置文件中对应的值和HttpEncodingPropertie绑定起来;并把HttpEncodingProperties加入到IOC容器中 ({//Spring底层@Condition注解,根据不同的条件,如果满足指定的条件,整个配置类里面的配置就会生效 判断当前应用是否是web应用,如果是 当前配置生效 CharacterEncodingFilter.class})// 判断当前项目有没有这个类;CharacterEncodingFilter:SpringMVC中进行乱码解决的过滤器 ({ ( prefix = "spring.http.encoding", value = {"enabled"}, matchIfMissing = true )//判断配置文件中是否存在某个配置spring.http.encoding.enabled;如果不存在,判断也是成立的 //即使配置文件中不配置spring.http.encoding.enabled=true,也是默认生效的 public class HttpEncodingAutoConfiguration { //它已经和springboot的配置文件映射了 private final HttpEncodingProperties properties; //只有一个有参构造器的情况下,参数的值就会从容器中取 public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) { this.properties = properties; } //给容器中添加一个组件,这个组件中的某个值需要从properties中获取 CharacterEncodingFilter.class}) //容器中如果没有,就加载此配置 ({ 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类中封装;配置文件能配置什么就可以参照某个功能对应的属性类
prefix = "spring.http.encoding") //从配置文件中获取指定的值和bean的属性进行绑定 (public class HttpEncodingProperties { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
精髓:
1)SpringBoot启动会加载大量的自动配置类
2)看需要的功能有没有SpringBoot默认写好的自动配置类
3)再看自动配置类中到底配置了哪些组件;(只要包含需求的组件,就不需要配置)
4)给容器中自动添加配置类添加组件时,会从properties类中获取某些属性。可以在配置文件中指定这些属性的值;
xxxAutoConfiguration:自动配置类
给容器中添加组件
xxxProperties:封装配置文件中相关属性
2、细节
1、@Conditional派生注解(Spring注解版原生的@Conditional作用)
作用:必须是@Conditional指定的条件成立,才给容器中添加组件,配置类里所有内容才生效
@Conditional扩展注解 | 作用(判断是否满足当前指定条件) |
---|---|
@ConditionalOnjava | 系统的java版本是否符合要求 |
@ConditionalOnBean | 容器中存在指定Bean |
@ConditionalOnMissingBean | 容器中不存在指定Bean |
@ConditionalOnExpression | 满足SpEL表达式指定 |
@ConditionalOnClass | 系统中有指定的类 |
@ConditionalOnMissClass | 系统中没有指定的类 |
@ConditionalOnSingleCandidate | 容器中只有一个指定的Bean,或者这个Bean是首选Bean |
@ConditionalOnProperty | 系统中指定的属性是否有指定的值 |
@ConditionalOnResource | 类路径下是否存在指定资源文件 |
自动配置类必须在一定条件下才能生效
可以通过debug=true属性,让控制台打印配置报告,这样就知道哪些自动配置类生效
Positive matches:自动匹配的内容
Negative matches:没有自动匹配的内容
三、日志
1、日志框架
日志门面(抽象层) | 日志实现 |
---|---|
Log4j JUL(java.util.logging) Log4j2 Logback |
左边选门面(抽象层),右边选一个实现
日志门面:SLF4J
日志实现:Logback
SpringBoot选用SLF4J和logback
2、SLF4J使用
1、如何整合使用
统一日志框架
统一:
1、将其他日志框架排除
2、用中间包替换原有日志框架
3、再导入slf4j其他的实现
SpringBoot能自动适配所有的日志,而且底层使用的是slf4j+logback的方式记录日志,引入其他框架的时候,只要把这个框架依赖的日志排除掉
logging.level.com.xxx=trace //设置log默认级别 logging.path=指定目录 logging.file=指定文件名 #如果path、file都不指定,只会在控制台输出 #在控制台输出的日志的格式 logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n #指定文件中日志输出的格式 logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n #日志输出格式: %d:日期时间 %thread:县成名 %-5level:级别从左显示5个字符宽度 %logger{50}:logger名字最长50个字符,否则按句点分割 %msg:日志消息 %n:换行符
2、指定配置
给类路径下放上每个日志框架自己的配置文件即可;
Logging System | Customization |
---|---|
Logback | logback-spring.xml ,logback-spring.groovy ,logback.xml orlogback.groovy |
Log4j2 | log4j2-spring.xml orlog4j2.xml |
JDK(Java Util Logging) | logging.properties |
logback.xml:直接被日志框架识别
logback-spring.xml:日志框架就不直接加载日志的配置项,由SpringBoot解析就可以使用高级功能,例:
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<springProfile name="dev">
<!--可以指定某段配置旨在某个环境下生效-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ---> [%thread] ---> %-5level %logger{50} - %msg%n</pattern>
</springProfile>
<springProfile name="!dev">
<!--可以指定某段配置旨在某个环境下生效-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} === [%thread] === %-5level %logger{50} - %msg%n</pattern>
</springProfile>
</appender>
SpringBoot对静态资源的映射规则:
1、所有的/webjars/**,都去classpath:/META-INF/resources/webjars/查找资源;
webjars:以jar包的方式引入静态资源;
<!--引入jquery-web.jar在访问的时候只要写webjars下面资源的名称即可-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1-1</version>
</dependency>
localhost:8080/webjars/jquery/3.3.1-1/jquery.js
2)"/**"访问当前项目的任何资源(静态资源的文件夹)
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/",
"/" 当前项目跟路径
3)欢迎页:静态资源文件夹下的所有index.html;被/**映射
4)所有的**/favicon.ico 都是在静态资源文件下找,(title上的图标)
四、WEB开发
1、模板引擎
引入thymleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
切换thymeleaf版本
<properties>
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<!-- 布局功能的支持程序,thymeleaf3主程序,layout2以上版本支持 -->
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>
2、Thymeleaf使用&语法
只要把HTML页面放在classpath:/templates/ , thymeleaf就能自动渲染
使用
1、导入thymeleaf的名称空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
2、使用thymeleaf语法:
1)th:text:改变当前元素里面文本内容
th:可以用任意html属性替换原生的html属性
2)表达式
表达式语法 ${...} : 获取变量值 = OGNL表达式 1)获取对象属性、调用方法 2)使用内置对象,例如:ctx、vars、locale、request、response、session、servletContext ${session.foo} 3)内置工具对象,例如:execInfo、messages、uris、conversions、dates、numbers... *{...} : 变量选择表达式,和${}在功能上一样 补充:配合th:object="${session.user}",在当前标签中就可以使用*{lastName}代替${session.user.lastName} #{...}:获取国际化内容 @{...}:定义URL链接 @{/order/process(execId=${execId},execType='FAST')} ~{...}:片段引用表达式 <div th:insert="_{commons :: main}">...</div> 字面量、文本操作、数学运算、布尔运算、比较运算、条件运算(三元运算符)、特殊操作(例:不操作:_)
4、SpringMVC自动配置
1)27.1.1 Spring MVC auto-configuration
Spring Boot自动配置好了SpringMVC
Inclusion of
ContentNegotiatingViewResolver
andBeanNameViewResolver
beans.自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何渲染(转发/重定向 ))
ContentNegotiatingViewResolver :组合所有的视图解析器
可以给自己的容器中添加一个视图解析器,就会自动组合进来
Support for serving static resources, including support for WebJars (see below).静态资源文件家路径webjars
自动注册了 of
Converter
,GenericConverter
,Formatter
beans.Converter:转换器:public String hello(User user)
Formatter:格式化器,自定义格式化转换器,只需要放入容器中
Support for
HttpMessageConverters
(see below).HttpMessageConverters:SpringMVC转换Http请求和响应:User--json
是从容器中确定;获取所有的HttpMessageConverter;
自定义HttpMessageConverter只需要放入容器中(@Bean / @Component)
Automatic registration of
MessageCodesResolver
(see below):定义错误代码生成规则Static
index.html
support. 静态首页访问Custom
Favicon
support (see below).Automatic use of a
ConfigurableWebBindingInitializer
bean (see below).可以配置一个
ConfigurableWebBindingInitializer
替换默认(添加到容器)初始化WebDataBinder;请求数据==>JavaBean
2)扩展SpringMVC
<mvc:view-controller path="/hello" view-name="success"/> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/hello"/> <bean>自定义拦截器</bean> </mvc:interceptor> </mvc:interceptors>
编写配置类(@Configuration),是WebMvcConfigurerAdapter类型;不能标注@EnableWebMvc
//使用WebMvcConfigurerAdapter可以扩展SpringMVC的功能 public class MyMvcConfig extends WebMvcConfigurerAdapter { public void addViewControllers(ViewControllerRegistry registry) { //super.addViewControllers(registry) //浏览器发送/hello请求到hello registry.addViewControllers("/hello").setViewName("hello"); } }
原理:
1)WebMvcAutoConfiguration是SpringMVC的自动配置类
2)在做其他自动配置时会导入:@Import(EnableWebMvcConfiguration.class)
3)容器中所有的WebMvcAutoConfiguration都会被加载
3)全面接管SpringMVC
SpringBoot对SpringMVC自动配置全抛弃,使用自定义配置
只需要在配置类添加@EnableWebMvc就可以全面接管SpringMVC
失效原理:
1)@EnableWebMvc导入了@Import(DelegatingWebMvcConfiguration.class)
2)继承了WebMvcAutoConfiguration,在这个类上标明了@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)表明容器中没有这个组件时,自动配置才生效
5、如何修改SpringBoot默认配置
模式1)SpringBoot自动配置组件的时候,先看容器中是否含有自定义配置(@Bean / @Component);包含自定义配置优先使用自定义配置,不包含试用自动配置。
如果有些组件可以有多个ViewResolver,将用户配置的和自定义配置组合起来
2) 待更新