Springboot2(2)属性配置讲解和自定义属性配置

版权声明:转载请注明出处 https://blog.csdn.net/cowbin2012/article/details/85237502

[源码地址](https://gitee.com/cowboy2016/springboot2-open)

springboot2系列教程

在使用spring boot过程中,可以发现项目中只需要极少的配置就能完成相应的功能,这归功于spring boot中的模块化配置,在pom.xml中依赖的每个Starter都有默认配置,而这些默认配置足以满足正常的功能开发。

重点

多环境的配置方法

@value支持的7种内容注入,还List,Map类型的注入,设置默认值的方法

@ConfigurationProperties,@Profile的使用

属性配置详解

参数引用与random随机数方法的使用

在application.yml内可以直接通过${}引用其他属性的值,如下:

myframe:
      name: tom
      desc: ${myframe.name} is boy

获取随机数,可以通过${random}

#获取随机字符串
myframe.randomValue: ${random.value}
​
#获取随机字符串:${random.value}
#获取随机int:${random.int}
#获取10以内的随机数:${random.int(10)}
#获取10-20的随机数:${random.int[10,20]}
#获取随机long:${random.long}
#获取随机uuid:${random.uuid}

多环境配置

实际开发中可能会有不同的环境,有开发环境、测试环境、生成环境。对于每个环境相关配置都可能有所不同,如:数据库信息、端口配置、本地路径配置等。

方法一

在application.yml同目录下新建一下三个文件:

application-dev.yml      //开发环境的配置文件

在application.yml添加:

spring.profiles.active: dev

用命令运行jar包启动应用的时候,也可以指定相应的配置

java -jar myframe-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev

方法二

在application.yml通过---

server.port: 8001
spring.profiles: node1
---
spring.profiles: node2
server.port: 8002

激动环境

用命令运行jar包启动应用的时候,可以指定相应的配置

java -jar myframe-0.0.1-SNAPSHOT.jar --spring.profiles.active=node1

或者在application.yml

spring.profiles.active: test

配置方式和优先级

这些方式优先级如下:
a. 命令行参数
b. 来自java:comp/env的JNDI属性
c. Java系统属性(System.getProperties())
d. 操作系统环境变量
e. RandomValuePropertySource配置的random.*属性值
f. jar外部的application-{profile}.properties或application.yml(带spring.profile)配置文件
g. jar内部的application-{profile}.properties或application.yml(带spring.profile)配置文件
h. jar外部的application.properties或application.yml(不带spring.profile)配置文件
i. jar内部的application.properties或application.yml(不带spring.profile)配置文件
j. @Configuration注解类上的@PropertySource
k. 通过SpringApplication.setDefaultProperties指定的默认属性

注:命令行参数这种jar包指定参数启动应用的方式,可能是不安全的,我们可以设置禁止这种方式启动应用,如下:

springApplication.setAddCommandLineProperties(false);

自定义属性配置

在application.yml中添加自定义属性配置

myframe:
   user:
      name: tom
      age: 29
      address: 广东广州天河
      uuid: ${random.uuid}
      desc: ${myframe.user.name} is ${myframe.user.age} years old
      date: 2018/09/20
      hobby[0]: 打球
      hobby[1]: 写代码

@Value()加载

@Component
@Data
class User{
    @Value("${myframe.user.name}")
    private String name;
    @Value("${myframe.user.age}")
    private int age;
    @Value("${myframe.user.address}")
    private String address;
    @Value("${myframe.user.phone:13422337766}")
    private String phone;
    @Value("${myframe.user.desc}")
    private String desc;
}

SpringBoot如果我们使用了@Value来从配置文件读取值的话 ,就会报错

@Value(${myframe.user.phone:13422337766}) 配置项指定了13422337766默认值

@value支持注入内容

  • (1)注入普通字符;

  • (2)注入操作系统属性;

  • (3)注入表达式运算结果;

  • (4)注入其他Bean的属性;

  • (5)注入文件内容;

  • (6)注入网址内容;

  • (7)注入属性文件;

import org.springframework.core.io.Resource;
​
@Data
@Component
@PropertySource("classpath:application.yml")
public class ValueModel {
​
    @Value("I LOVE YOU!") //注入普通字符串
    private String normal;
​
    @Value("#{systemProperties['os.name']}") //注入操作系统属性
    private String osName;
​
    @Value("#{T(java.lang.Math).random() * 100.0}") //注入表达式结果
    private String randomNumber;
​
    @Value("#{user.address}") //注入其他Bean属性
    private String address;
​
    @Value("classpath:/test.txt") //注入文件资源
    private Resource testFile;
​
    @Value("http://www.baidu.com") //注入网址资源
    private Resource testUrl;
​
    @Value("${myframe.user.name}") // 注入配置文件
    private String userName;
​
    @Autowired // 注入配置文件
    private Environment environment;
​
    @Bean // 注入配置文件
    public static PropertySourcesPlaceholderConfigurer propertyConfigurer(){
        return new PropertySourcesPlaceholderConfigurer();
    }
​
    public void outputResource(){
        try {
            System.out.println(normal);
            System.out.println(osName);
            System.out.println(randomNumber);
            System.out.println(address);
            System.out.println(IOUtils.toString(testFile.getInputStream()));
            System.out.println(IOUtils.toString(testUrl.getInputStream()));
            System.out.println(userName);
            System.out.println(environment.getProperty("myframe.user.name"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

@ConfigurationProperties(prefix="")

@Component
@ConfigurationProperties(prefix = "myframe.user")
@Data
class PreUser{
    private String name;
    private int age;
    private String address;
    private String phone;
    private String desc;
    private Date date;
    private List<String> hobby;
}

@ConfigurationProperties可以对基本数据类型实现自动封装,可以封装格式为yyyy/MM/dd的日期

@Profile("")

public interface Person {
    void say();
}
​
@Component
@Profile("test")
@Slf4j
public class Student implements Person{
    @Override
    public void say() {
        log.info("我是学生");
    }
}
​
@Component
@Slf4j
@Profile("dev")
public class Teacher implements Person {
    @Override
    public void say() {
        log.info("我是老师");
    }
}

使用方法

    @Autowired
    private Person person;
​
    @RequestMapping("/user")
    public String user(){
        person.say();
        return "";
    }

spring.profiles.active: test时,打印"我是学生"

spring.profiles.active: dev时,打印"我是老师"

源码地址:https://gitee.com/cowboy2016/springboot2-open

猜你喜欢

转载自blog.csdn.net/cowbin2012/article/details/85237502