Spring属性赋值

1. @Value

支持三种方式:
  1. 基本数值
  2. 可以写SpEL: #{}
  3.可以写${},去配置文件【properties】中的值

代码如下:
Girl.java实体类

public class Girl {
    //使用@Value赋值
    //1. 基本数值
    //2. 可以写SpEL: #{}
    //3.可以写${},去配置文件【properties】中的值(在运行环境变量里的值)
    @Value("NAME")
    private String name;

    @Value("#{65+8}")
    private Integer age;


    @Value("${ggg}")
    private String weiXin;

    public Girl() {
    }

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

    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 getWeiXin() {
        return weiXin;
    }

    public void setWeiXin(String weiXin) {
        this.weiXin = weiXin;
    }

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

2. @PropertySource加载配置文件

MainConfig_properties.java

//使用PropertySource读取外部配置文件中的k/v保存到环境变量中
@PropertySource(value = {"classpath:/person.properties"})
@Configuration
public class MainConfig_properties {

    @Bean
    public Girl girl(){
        return new Girl();
    }

}

person.properties

xixixii=gjdkjgkjd
ggg=sgfsdfsd

你可能感兴趣的:(Spring属性赋值)