加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Spring boot Value注入 未整理 待完善

发布时间:2020-12-15 01:51:34 所属栏目:大数据 来源:网络整理
导读:功能 @ConfigurationProperties @Value注入方式 批量注入配置文件中的属性 一个个指定松散绑定(松散语法) 支持 不支持SpEL 不支持 支持JSR303数据校验(@Validated) 支持 不支持复杂类型封装 支持 不支持应用场景: 配置文件yml还是properties它们都能获取

功能 @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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读