spring 之 属性赋值

  给属性赋值有两种方式:@Value("属性的值") @PropertySource 
   @Value三种方式:
    1)基本数值
    2) SpEL 表达式 #{}
    3)${} 取出配置文件的值(在运行时环境变量中的值 Environment)
  @PropertySource 读取外部配置文件中的 key-value 保存到运行时环境变量中,
  加载完外部配置文件以后,使用 ${} 取配置文件中的值

在配置文件 person.properties中有 person.nickName=奥里给

public class Person {
 
    /**
     * 使用 @Value 赋值
     * 1.基本数值
     * 2.SpEL 表达式 #{}
     * 3.${} 取出配置文件的值(在运行环境变量中的值 Environment)
     */
 
    @Value("小丁")
    private String name;
    @Value("#{27}")
    private Integer age;
    @Value("${person.nickName}")
    private String nickName;
 
    public Person() {
    }
 
    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
 
    public String getNickName() {
        return nickName;
    }
 
    public void setNickName(String nickName) {
        this.nickName = nickName;
    }
 
    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;
    }
 
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", nickName='" + nickName + '\'' +
                '}';
    }
}
@PropertySource(value = {"classpath:/person.properties"}, encoding = "utf-8")
@Configuration
public class MainConfigOfPropertyValues {
 
    @Bean
    public Person person() {
 
        return new Person();
    }
}
public class IOCTestPropertyValue {
 
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
 
    @Test
    public void test01() {
        printBeans(context);
        Person person = (Person) context.getBean("person");
        System.out.println("---->"+person);
 
        ConfigurableEnvironment environment = context.getEnvironment();
        String property = environment.getProperty("person.nickName");
        System.out.println(property);
        context.close();
    }
 
    private void printBeans(AnnotationConfigApplicationContext context) {
        String[] beanDefinitionNames = context.getBeanDefinitionNames();
        for (String name : beanDefinitionNames) {
            System.out.println(name);
        }
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值