zoukankan      html  css  js  c++  java
  • Spring boot Value注入 未整理 待完善

    Springboot 热部署
    Springboot为开发者提供了一个名叫 spring-boot-devtools来使Springboot应用支持热部署,提供开发者的开发效率,无需手动重启Spring Boot应用

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools -->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <version>2.1.3.RELEASE</version>
    </dependency>
    

      


    导入配置文件处理器,以后会出现提示

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-configuration-processor -->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <version>2.1.3.RELEASE</version>
    </dependency>
    

      


    注意: Properties配置文件在idea中默认utf-8可能会乱码


    配置文件中,我们可以自己制定配置数据源
    通过type来选择使用哪种数据库


    Springboot自动配置原理
    1. Springboot启动的时候加载主配置类,开启了自动配置功能@EnableAutoConfiguration
    2. @EnableAutoConfiguration的作用
    3.

    @Value获取值和@ConfigurationProperties获值比较


    配置文件是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<String,Object> maps;
    private List<Object> 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
    @Validated
    public 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<String,Object> maps;
    private List<Object> 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 profile
    Profile是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: dev
    server:
    port: 8090

    ---

    #生产环境

    spring:
    profiles: product
    server:
    port: 9090

    ---

    #默认环境

    spring:
    profiles: default
    server:
    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.properties
    1
    springboot的所有配置都可以在命令行上指定,多个配置使用空格分开,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这个配置,如果缺失则默认为true
    public 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<ConfigurableServletWebServerFactory>, 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<Locale, Charset> mapping;
    .......
    }

    application.yml

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

    Springboot常用的模板引擎
    JSP、Velecity、Freemaker、Thymeleaf


    jdbcTemplate

  • 相关阅读:
    lua for循环
    多面体的欧拉公式
    流形(Manifold)初步
    Laplace算子和Laplacian矩阵
    多重网格方法(Multigridmethod)
    多重网格方法
    谷歌浏览器兼容IE插件
    伽辽金法
    共轭梯度法
    有限元分析
  • 原文地址:https://www.cnblogs.com/qianjinyan/p/6628650.html
Copyright © 2011-2022 走看看