Spring Boot自动配置与自定义配置方法

Spring Boot自动配置原理

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。它使用“习惯优于配置”的理念可以让你的项目快速运行部署。使用Spring Boot可以不用或者只需要很少的Spring配置。

Spring Boot核心的功能就是自动配置。它会根据在类路径中的jar、类自动配置Bean,当我们需要配置的Bean没有被Spring Boot提供支持时,也可以自定义自动配置。

自动配置原理

spring-boot-starter-web

spring-boot-starter:spring-boot场景启动器;帮我们导入了web模块正常运行所依赖的组件;
1.Spring Boot将所有的功能场景都抽取出来,做成一个个的starters(启动器),只需要在项目里面引入这些starter相关场景的所有依赖都会导入进来。要用什么功能就导入什么场景的启动器

主程序类,主入口类

/**

  • @SpringBootApplication 来标注一个主程序类,说明这是一个Spring Boot应用
    */
    @SpringBootApplication
    public class HelloWorldMainApplication {
    public static void main(String[] args) {
    // Spring应用启动起来
    SpringApplication.run(HelloWorldMainApplication.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:Spring Boot的配置类;

标注在某个类上,表示这是一个Spring Boot的配置类;
@Configuration:配置类上来标注这个注解;
配置类 ----- 配置文件;配置类也是容器中的一个组件;@Component

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

以前我们需要配置的东西,Spring Boot帮我们自动配置;@EnableAutoConfiguration告诉SpringBoot开启自动配置功能;这样自动配置才能生效;
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
@AutoConfigurationPackage:自动配置包
@Import(AutoConfigurationPackages.Registrar.class):
Spring的底层注解@Import,给容器中导入一个组件;导入的组件由AutoConfigurationPackages.Registrar.class;

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

@Import(EnableAutoConfigurationImportSelector.class);
给容器中导入组件
EnableAutoConfigurationImportSelector:导入哪些组件的选择器;
将所有需要导入的组件以全类名的方式返回;这些组件就会被添加到容器中;
会给容器中导入非常多的自动配置类(xxxAutoConfiguration);就是给容器中导入这个场景需要的所有组件,并配置好这些组件;

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

SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class,classLoader);
==Spring Boot在启动的时候从类路径下的META-INF/spring.factories中获取EnableAutoConfiguration指定的值,将这些值作为自动配置类导入到容器中,自动配置类就生效,帮我们进行自动配置工作;==以前我们需要自己配置的东西,自动配置类都帮我们;

J2EE的整体整合解决方案和自动配置都在spring-boot-autoconfigure-1.5.11.RELEASE.jar;
Spring Boot自动配置其实是基于Spring 4.x提供的条件配置(Conditional)实现的。
pring Boot启动的时候加载主配置类,开启了自动配置功能 @EnableAutoConfiguration

@EnableAutoConfiguration 作用

  • 利用EnableAutoConfigurationImportSelector给容器中导入一些组件
  • 可以查看selectImports()方法的内容;
  • List configurations = getCandidateConfigurations(annotationMetadata, attributes);获取候选的配置
  • SpringFactoriesLoader.loadFactoryNames()
    扫描所有jar包类路径下 META-INF/spring.factories
    把扫描到的这些文件的内容包装成properties对象
    从properties中获取到EnableAutoConfiguration.class类(类名)对应的值,然后把他们添加在容器中
    将 类路径下 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.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,

每一个这样的 xxxAutoConfiguration类都是容器中的一个组件,都加入到容器中;用他们来做自动配置;

以HttpEncodingAutoConfiguration(Http编码自动配置)为例解释自动配置原理

@Configuration //表示这是一个配置类,以前编写的配置文件一样,也可以给容器中添加组件
@EnableConfigurationProperties(HttpEncodingProperties.class) //启动指定类的ConfigurationProperties功能;将配置文件中对应的值和HttpEncodingProperties绑定起来;并把HttpEncodingProperties加入到ioc容器中
@ConditionalOnWebApplication //Spring底层@Conditional注解(Spring注解版),根据不同的条件,如果满足指定的条件,整个配置类里面的配置就会生效;判断当前应用是否是web应用,如果是,当前配置类生效
@ConditionalOnClass(CharacterEncodingFilter.class) //判断当前项目有没有这个类CharacterEncodingFilter;SpringMVC中进行乱码解决的过滤器;
@ConditionalOnProperty(prefix = “spring.http.encoding”, value = “enabled”, matchIfMissing = true) //判断配置文件中是否存在某个配置 spring.http.encoding.enabled;如果不存在,判断也是成立的
//即使我们配置文件中不配置pring.http.encoding.enabled=true,也是默认生效的;
public class HttpEncodingAutoConfiguration {
//他已经和SpringBoot的配置文件映射了
private final HttpEncodingProperties properties;
//只有一个有参构造器的情况下,参数的值就会从容器中拿
public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {
this.properties = properties;
}
@Bean //给容器中添加一个组件,这个组件的某些值需要从properties中获取
@ConditionalOnMissingBean(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类中获取的,这些类里面的每一个属性又是和配置文件绑定的;
\所有在配置文件中能配置的属性都是在xxxxProperties类中封装者‘;配置文件能配置什么就可以参照某个功能对应的这个属性类

@ConfigurationProperties(prefix = “spring.http.encoding”) //从配置文件中获取指定的值和bean的属性进行绑定
public class HttpEncodingProperties {
public static final Charset DEFAULT_CHARSET = Charset.forName(“UTF-8”);

精髓

  • SpringBoot启动会加载大量的自动配置类
  • 我们再来看这个自动配置类中到底配置了哪些组件;(只要我们要用的组件有,我们就不需要再来配置了)
  • 给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。我们就可以在配置文件中指定这些属性的值;
  • xxxxAutoConfigurartion:自动配置类;
  • 给容器中添加组件;
  • xxxxProperties:封装配置文件中相关属性;

细节

1、@Conditional派生注解(Spring注解版原生的@Conditional作用)
作用:必须是@Conditional指定的条件成立,才给容器中添加组件,配置配里面的所有内容才生效;

@Conditional扩展注解

作用(判断是否满足当前指定条件)

@ConditionalOnJava

系统的java版本是否符合要求

@ConditionalOnBean

容器中存在指定Bean;

@ConditionalOnMissingBean

容器中不存在指定Bean;

@ConditionalOnExpression

满足SpEL表达式指定

@ConditionalOnClass

系统中有指定的类

@ConditionalOnMissingClass

系统中没有指定的类

@ConditionalOnSingleCandidate

容器中只有一个指定的Bean,或者这个Bean是首选Bean

@ConditionalOnProperty

系统中指定的属性是否有指定的值

@ConditionalOnResource

类路径下是否存在指定资源文件

@ConditionalOnWebApplication

当前是web环境

@ConditionalOnNotWebApplication

当前不是web环境

@ConditionalOnJndi

JNDI存在指定项

自定义配置

SpringBoot中免除了大部分手动配置,但是对于一些特定的情况,还是需要我们进行手动配置的,SpringBoot为我们提供了application.properties配置等文件,让我们可以进行自定义配置,来对默认的配置进行修改,以适应具体的生产情况,当然还包括一些第三方的配置。几乎所有配置都可以写到application.peroperties文件中,这个文件会被SpringBoot自动加载,免去了我们手动加载的烦恼。Spring Boot 支持使用YAML语言的配置文件,YAML是以数据位中心的语言,所以使用application.yml作为全局配置也是同样的效果,如果使用YAML替代properties注意写法,冒号后面要加个空格,否则会解析不出来。

引用XML文件配置

在实际项目中有的情况需要使用到XML配置文件,或者是你还不习惯用Java 配置的方式,那么你可以通过在入口启动类上加上@ImportResource(value = { “路径” })或者使用@ImportResource(locations= { “路径” }),一样的效果,多个XML文件的话你可以用逗号“,”分隔,就这样轻而易举的引用XML配置。

引入多个@Configuration 配置类

在实际项目中可能不会把所有的配置都放在一个配置类(用@Configuration注解的类)中,可能会分开配置。这时可以用@Import注解引用。

引用自定义properties

Spring Boot使用全局配置(application.properties)提供了很多的默认的配置属性。在开发的时候,大多数会用到自定义的一些配置属性,例如:指定上传文件保存的路径,定义:file.upload.stor-path=E:/test/,Spring Boot 提供了@Value注解获取properties中的属性,还提供了基于类型安全的配置方式,通过@ConfigurationProperties将properties属性注入到一个Bean中,在1.4以上版本官方不建议使用@ConfigurationProperties来指定properties文件位置。接下来请看实例:
在pom.xml中加入以下依赖:

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

第一种:
(1) 在src/main/resources下新建application.properties文件并加入以下代码:

file.upload.stor-path=E:/test/

(2)直接使用@Value注解方式,具体代码如下:

package com.chengli.springboot.helloworld;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
public class SampleController {
@Value(value = “${file.upload.stor-path}”)
private String storPath;
@RequestMapping("/")
String home() {
return “Hello World! file.upload.stor-path为:” + storPath;
}
public static void main(String[] args) throws Exception {
SpringApplication springApplication = new SpringApplication(SampleController.class);
springApplication.run(args);
}
}

第二种:
属性配置放在application.properties文件中,使用@ConfigurationProperties将配置属性注入到Bean中,代码如下:
(1)定义FileUploadProperties类

package com.chengli.springboot.helloworld;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = “file.upload”)
public class FileUploadProperties {
private String storPath;
public String getStorPath() {
return storPath;
}
public void setStorPath(String storPath) {
this.storPath = storPath;
}
}

(2)入口启动类代码如下:

package com.chengli.springboot.helloworld;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
public class SampleController {
@Autowired
private FileUploadProperties fileUploadProperties;
@RequestMapping("/")
String home() {
return “Hello World! file.upload.stor-path为:” + fileUploadProperties.getStorPath();
}
public static void main(String[] args) throws Exception {
SpringApplication springApplication = new SpringApplication(SampleController.class);
springApplication.run(args);
}
}

注意:这里我对FileUploadProperties使用了@Component注解,如果没有使用@Component注解,则需要在入口启动类上加上@EnableConfigurationProperties注解。Spring Boot 在properties文件中支持使用SpEL表达式,可以进行校验(校验注解使用的是javax.validation)等操作。
例如以下:

  • 随机数
    test.int.random=${random.int}
  • 数组校验
    test.int.random[0]=spring boot druid sessionStatMap is full配置关闭 关闭springboot自动配置_spring{random.int}
  • 校验
    @NotNull
    private String storPath;

4.外部化配置(配置方式与优先级)
Spring Boot 允许外化配置,Spring Boot使用了一个特别的PropertySource次序来允许对值进行覆盖,覆盖的优先级顺序如下:
(1)Devtools全局设置主目录(~ /.spring-boot-devtools.properties 为活跃的)。
(2)@TestPropertySource注解在Test。
(3)@SpringBootTest#properties 注解在Test。
(4)命令行参数。
(5)从SPRING_APPLICATION_JSON属性(内联JSON嵌入在一个环境变量或系统属性)。
(6)ServletConfig init参数。
(7)ServletContext init参数。
(8)JNDI属性java:comp/env。
(9)Java系统属性(System.getProperties())。
(10)操作系统环境变量。
(11)RandomValuePropertySource配置的random.*属性值
(12)打包在jar以外的application-{profile}.properties或application.yml配置文件
(13)打包在jar以内的application-{profile}.properties或application.yml配置文件
(14)打包在jar以外的application.properties或application.yml配置文件
(15)打包在jar以内的application.properties或application.yml配置文件
(16)@configuration注解类上的@PropertySource。
(17)默认的属性(使用SpringApplication.setDefaultProperties指定)。

a) 通过命令行来修改默认参数,例如:
启动命令:java -jar *.jar --name=“chengli”
以上的意思是,将name值修改为:chengli
b) 通过命令行来设置加载properties 例如:
java -jar *.jar --spring.profiles.active=dev
5.application.properties文件按优先级,优先级高的会覆盖优先级低的
优先级顺序如下:
(1)当前目录下的一个/config子目录
(2)当前目录
(3)一个classpath下的/config包
(4)classpath根目录