当前位置: 代码迷 >> 综合 >> spring中@PropertySource和@Value注解使用
  详细解决方案

spring中@PropertySource和@Value注解使用

热度:100   发布时间:2023-10-26 08:25:36.0

@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 {@Beanpublic 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;}@Overridepublic String toString() {return "Person{" +"id=" + id +", name='" + name + '\'' +", email='" + email + '\'' +'}';}
}

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

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

 

  相关解决方案