《B站-Spring源码解析》学习笔记(三)——属性赋值

视频地址:https://www.bilibili.com/video/BV1oW41167AV
对应代码Git库地址:https://github.com/whh306318848/spring-annotation.git

  1. 使用@Value注解对Bean的属性进行赋值:
    1.1. 使用基本数值进行赋值
    1.2. 可以使用Spring表达式SpEL(即#{})进行赋值
    1.3. 可以使用${}读取配置文件或环境变量中的值
  2. 如果是使用xml配置文件为Bean赋值的方式,在xml文件中引用外部配置文件需要先在配置文件中加入"context"名字空间,然后使用"context:property-placeholder"标签的location属性指定要导入的外部配置文件
<context:property-placeholder location="classpath:person.properties" />
  1. 使用注解方式的过程与使用xml配置文件类似
    3.1. 首先,需要在配置类上通过@PropertySource注解导入配置文件,该注解的value属性用于指定配置文件的路径,是一个String数组,可以从类路径(classpath)开始,也可以从文件路径(file)开始
    3.2. 然后,在Bean类中使用${}读取配置文件中的值
// 使用@PropertySource读取外部配置文件中的key/value保存到运行的环境变量中,加载完外部的配置文件以后,使用${}去除配置文件的值
@PropertySource(value = {"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValues {

    @Bean
    public Person person() {
        return new Person();
    }
}
public class Person {
    // 使用@Value赋值:
    // 1、基本数值
    // 2、可以写Spring表达式SpEL:#{}
    // 3、可以使用${}取配置文件【.properties】中的值(在运行环境变量中的值)
    @Value("张三")
    private String name;
    @Value("#{20-2}")
    private Integer age;
    @Value("${person.nickName}")
    private String nickName;

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public Person() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", nickName='" + nickName + '\'' +
                '}';
    }
}

3.3。 @PropertySource注解的作用是读取外部配置文件中的key/value保存到运行的环境变量中,所以除了在Bean类中使用${}读取配置文件的值之外,还可以使用ConfigurableEnvironment的getProperty方法读取

ConfigurableEnvironment environment = applicationContext.getEnvironment();
String property = environment.getProperty("person.nickName");
System.out.println(property);
  1. @PropertySource注解是一个可重复组件,如果需要引入多个配置文件,有两种方法,分别是:
    4.1. 使用@PropertySource注解,在其value属性中填入配置文件路径数组;
    4.2. 使用@PropertySources注解,其值是@PropertySource数组
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值