美文网首页spring 相关
spring注解 -- @Value赋值

spring注解 -- @Value赋值

作者: aix91 | 来源:发表于2018-12-31 17:10 被阅读0次

1. 语法说明

为bean的属性添加初始值。
赋值的方式

  1. 添加基本值: @Value("hi")
  2. 使用SpEL:#{}, 如:#{1+2}
  3. ${key}. 取出配置文件中的值(在运行时环境变量中取值)

2. 实例

public class Animal {
    @Value("black")
    private String color;
    @Value("#{2+1}")
    private int age;
    @Override
    public String toString() {
        return String.format("{color:%s, age:%s}", color, age);
    }
}

定义文件配置文件路径

@PropertySource(value = {"classpath:/animal.properties"})//读取外部配置文件,保存到运行环境变量中
@Configuration
public class MyBeanLifeCycle {
    @Bean(name = "animal")
    public Animal animal() {
        Animal animal = new Animal();
        return animal;
    }
}

从配置文件中取值

    @Value("${nickname}")//配置文件中的key
    private String nickname;

相关文章

网友评论

    本文标题:spring注解 -- @Value赋值

    本文链接:https://www.haomeiwen.com/subject/yqhwlqtx.html