spring中@PropertySource和@Value注解使用

@PropertySource注解用于导入外部配置文件,以使用导入的属性

下面是配置文件中的一个属性

zhang.email=zhang@163.com

下面是配置类,在配置类中使用@PropertySource注解导入配置文件 

import com.annotation.entities.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@PropertySource(value = "classpath:Person.properties")
@Configuration
public class MainConfigPropertie {

    @Bean
    public Person person(){
        return new Person();
    }

}

@Value注解用于为属性赋值,可以赋值为常量,或者使用SpEL表达式,也可以使用${}去上面配置类中导入的配置文件中的属性

import org.springframework.beans.factory.annotation.Value;

public class Person {

    public Person() {
        System.out.println("创建perosn对象");
    }

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

    private Integer id;

    @Value("小张")
    private String name;
    @Value("${zhang.email}")
    private String email;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

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

使用@PropertySource注解导入的配置文件中的属性回被放入到运行环境中,所以也可以直接使用运行时环境类获取配置文件中的属性

    @Test
    public void testValue(){
        ConfigurableEnvironment environment = annotationConfigApplicationContext.getEnvironment();
        String property = environment.getProperty("zhang.email");
        System.out.println(property);
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值