Spring boot Value注入 未整理 待完善

功能 @ConfigurationProperties @Value注入方式 批量注入配置文件中的属性 一个个指定松散绑定(松散语法) 支持 不支持SpEL 不支持 支持JSR303数据校验(@Validated) 支持 不支持复杂类型封装 支持 不支持应用场景: 配置文件yml还是properties它们都能获取到值 若只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value 若专门编写了一个javaBean来和配置文件进行映射,我们就直接使用@ConfigurationProperties

@ConfigurationProperties该注解可以将配置文件中配置的每一个属性的值,通过set方法映射到被注释的组件中(因此不可以缺少setter方法)

/** * 批量注入、松散绑定、数据校验、复杂类型封装 */@Component@ConfigurationProperties(prefix = "person1") //批量注入@Validated //数据校验public class Person { @Email private String lastName; private Integer age; private Boolean boss; private Date birth; private Map maps; private List lists; private Dog dog;//复杂类型封装

public void setLastName(String lastName) { this.lastName = lastName; } ......}public class Dog { private String name; private Integer age; public void setName(String name) { this.name = name; } public void setAge(Integer age) { this.age = age; }}

applicaton.yml

person1: lastName: 888888@qq.com #以下二种写法与上述等同(松散绑定): #last-name: 88888@qq.com #last_name: 88888@qq.com age: 18 boss: false birth: 2018/04/04 maps: {k1: v1,k2: v2} lists: - lisi - zhaoliu dog: name: 小狗 age: 12

@Value@Component@Validatedpublic class Person { @Email//数据校验无效 @Value("${person1.lastName}")//从环境变量、配置文件中获取值 private String lastName; @Value("#{11*2}")//使用SpEL表达式 private Integer age; @Value("true")//直接赋值 private Boolean boss; private Date birth; @Value("${person1.maps}")//不支持复杂类型,报错 private Map maps; private List lists; private Dog dog; ......}

@PropertySource、@ImportResource、@Bean//指明当前类为配置类,替代之前的Spring配置文件@Configuration//加载指定的配置文件@PropertySource(value = {"classpath:person.properties"})//SpringBoot项目没有Spring的配置文件,若要想自己编写Spring配置文件加载并生效,需要使用@ImportResoure注解标注在一个配置类上@ImportResource(locations = {"classpath:application.xml"})public class MyAppConfig {

@Bean //注册bean,默认是方法名作为id public Person person() { return new Person(); }}

SpringBoot给容器中添加组件的方式(推荐使用全注解的方式):

配置类@Configuration标注@ImportResoure加载Spring配置文件使用@Bean给容器中添加组件3.3 配置文件属性3.3.1 随机数RandomValuePropertySource:配置文件中可以使用随机数

${random.value}:随机数字与字母组合的字符串${random.uuid}:随机uuid${random.long}:随机long值${random.int}:随机int值${random.int(value)}:0~value之间的随机数${random.int(value,max)}:value~max之间的随机数这些随机数可以使用在配置文件或@Value注解中

person1: lastName: ${random.value} age: ${random.int(0,100)} #如果birthday不存在使用默认值2014/1/1 birth: ${birthday:2014/1/1}

3.3.2 profileProfile是Spring对不同环境提供不同配置功能的支持,可以通过激活、指定参数等方式快速切换环境,多环境有以下二种方式:

多个profile文件:格式是application-{profile}.properties/yml,例如application-dev.properties,SpringBoot默认加载application.propeties/yml配置文件,可以在该文件中激活不同的profile:spring.profiles.active=dev多个profile文档块模式application.yml:

#激活指定环境

spring: profiles: active: dev

---

#开发环境

spring: profiles: devserver: port: 8090

---

#生产环境

spring: profiles: productserver: port: 9090

---

#默认环境

spring: profiles: defaultserver: port: 8080

配置环境也可以在外部文件、命令行或jvm参数中指定,如使用命令行(- -spring.profiles.active=dev)或jvm参数(-Dspring.profiles.active=dev)来激活指定的profile。

3.3.3 配置文件加载顺序springboot 启动会扫描以下位置的application.properties或者application.yml文件作为Spring boot的默认配置文件

file:./config/file:./classpath:/config/classpath:/上述优先级由高到低,高优先级的配置会覆盖低优先级的配置,同时配置互补。项目打包好以后,我们可以使用命令行参数的形式,启动项目的时候来可以使用spring.config.location指定外部的配置文件位置:

java -jar spring-boot-0.0.1-SNAPSHOT.jar --spring.config.location=D:/application.properties1springboot的所有配置都可以在命令行上指定,多个配置使用空格分开,spring配置的优先级由高到低:

命令行参数来自java:comp/env的JNDI属性Java系统属性(System.getProperties())操作系统环境变量RandomValuePropertySource配置的random.*属性值jar包外部的application-{profile}.properties或application.yml(带spring.profile)配置文件jar包内部的application-{profile}.properties或application.yml(带spring.profile)配置文件jar包外部的application.properties或application.yml(不带spring.profile)配置文件jar包内部的application.properties或application.yml(不带spring.profile)配置文件@Configuration注解类上的@PropertySource通过SpringApplication.setDefaultProperties指定的默认属性4. 自动配置原理SpringBoot启动的时候加载主配置类(@SpringBootApplication),开启了自动配置功能@EnableAutoConfiguration@EnableAutoConfiguration的组合注解@AutoConfigurationPackage将该配置类包及子包路径下的所有组件扫描进Spring容器中@EnableAutoConfiguration的组合注解 @Import(AutoConfigurationImportSelector.class)注解导入AutoConfigurationImportSelector类,AutoConfigurationImportSelector类实现了DeferredImportSelector接口重写了selectImports方法,SpringFactoriesLoader.loadFactoryNames()扫描所有jar包类路径下 META-INF/spring.factories把扫描到的这些文件的内容包装成List对象,selectImports将这些自动配置类注册到容器中4.1 自动配置类案例分析以HttpEncodingAutoConfiguration 这个自动配置类为例:

@Configuration //标注该类为配置类@EnableConfigurationProperties(HttpEncodingProperties.class) //启动指定类的ConfigurationProperties功能,将配置文件中对应的值和HttpEncodingProperties绑定起来,并把HttpEncodingProperties加入到ioc容器中@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) //只有基于Servlet的web环境配置类才会生效@ConditionalOnClass(CharacterEncodingFilter.class) //判断当前项目有没有CharacterEncodingFilter这个类,CharacterEncodingFilter是SpringMVC中进行乱码解决的过滤器@ConditionalOnProperty(prefix = "spring.http.encoding",value = "enabled",matchIfMissing = true)//判断配置文件中是否存在spring.http.encoding.enabled这个配置,如果缺失则默认为truepublic class HttpEncodingAutoConfiguration {

private final HttpEncodingProperties properties; //将与SpringBoot配置文件映射过的HttpEncodingProperties注入 public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) { this.properties = properties; } //若容器中没有CharacterEncodingFilter这个组件就注入该bean @Bean @ConditionalOnMissingBean(CharacterEncodingFilter.class) public CharacterEncodingFilter characterEncodingFilter() { CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter(); filter.setEncoding(this.properties.getCharset().name()); filter.setForceRequestEncoding(this.properties.shouldForce(HttpEncodingProperties.Type.REQUEST)); filter.setForceResponseEncoding(this.properties.shouldForce(HttpEncodingProperties.Type.RESPONSE)); return filter; }

@Bean public LocaleCharsetMappingsCustomizer localeCharsetMappingsCustomizer() { return new LocaleCharsetMappingsCustomizer(this.properties); }

private static class LocaleCharsetMappingsCustomizer implements WebServerFactoryCustomizer,Ordered {

private final HttpEncodingProperties properties;

LocaleCharsetMappingsCustomizer(HttpEncodingProperties properties) { this.properties = properties; }

@Override public void customize(ConfigurableServletWebServerFactory factory) { if (this.properties.getMapping() != null) { factory.setLocaleCharsetMappings(this.properties.getMapping()); } }

@Override public int getOrder() { return 0; } }}

HttpEncodingProperties类映射配置文件中以spring.http.encoding为前缀的配置

@ConfigurationProperties( prefix = "spring.http.encoding")public class HttpEncodingProperties { public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

/** * Charset of HTTP requests and responses. Added to the "Content-Type" header if not * set explicitly. */ private Charset charset = DEFAULT_CHARSET;

/** * Whether to force the encoding to the configured charset on HTTP requests and * responses. */ private Boolean force;

/** * Whether to force the encoding to the configured charset on HTTP requests. Defaults * to true when "force" has not been specified. */ private Boolean forceRequest;

/** * Whether to force the encoding to the configured charset on HTTP responses. */ private Boolean forceResponse;

/** * Locale in which to encode mapping. */ private Map mapping; .......}

application.yml

#yml中可配置的属性也都是根据这些类中的属性来指定spring: http: encoding: enabled: true charset: utf-8 force: true force-request: true force-response: true mapping: UTF-8

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


这篇文章主要介绍了spring的事务传播属性REQUIRED_NESTED的原理介绍,具有一定借鉴价值,需要的朋友可以参考下。下面就和我一起来看看吧。传统事务中回滚点的使...
今天小编给大家分享的是一文解析spring中事务的传播机制,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起往下看吧。一定会有所收获...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区别,具有一定借鉴价值,需要的朋友可以参考下。下面就和我一起来看看吧。Spring Cloud Netfli...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。第一步:整合pom文件,在S...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。List 坑列表 = new ArrayList(2);...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓存的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇...
本篇内容主要讲解“Spring中的@Autowired和@Resource注解怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学...
今天小编给大家分享一下SpringSecurity怎么定义多个过滤器链的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家
这篇文章主要介绍“Spring的@Conditional注解怎么使用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Spring的@Con...
这篇文章主要介绍了SpringCloudGateway的熔断限流怎么配置的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇SpringCloud&nb...
今天小编给大家分享一下怎么使用Spring解决循环依赖问题的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考
这篇文章主要介绍“Spring事务及传播机制的原理及应用方法是什么”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Sp...
这篇“SpringCloudAlibaba框架实例应用分析”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价
本篇内容主要讲解“SpringBoot中怎么使用SpringMVC”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习...
这篇文章主要介绍“SpringMVC适配器模式作用范围是什么”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“SpringMVC
这篇“导入SpringCloud依赖失败如何解决”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家...
这篇文章主要讲解了“SpringMVC核心DispatcherServlet处理流程是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来
今天小编给大家分享一下SpringMVCHttpMessageConverter消息转换器怎么使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以...
这篇文章主要介绍“Spring框架实现依赖注入的原理是什么”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Spring框架...
本篇内容介绍了“Spring单元测试控制Bean注入的方法是什么”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下