spring中@PropertySource和@Value注解使用

忘是亡心i 2022-05-15 05:48 345阅读 0赞

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

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

  1. zhang.email=zhang@163.com

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

  1. import com.annotation.entities.Person;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.context.annotation.PropertySource;
  5. @PropertySource(value = "classpath:Person.properties")
  6. @Configuration
  7. public class MainConfigPropertie {
  8. @Bean
  9. public Person person(){
  10. return new Person();
  11. }
  12. }

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

  1. import org.springframework.beans.factory.annotation.Value;
  2. public class Person {
  3. public Person() {
  4. System.out.println("创建perosn对象");
  5. }
  6. public Person(Integer id, String name, String email) {
  7. this.id = id;
  8. this.name = name;
  9. this.email = email;
  10. }
  11. private Integer id;
  12. @Value("小张")
  13. private String name;
  14. @Value("${zhang.email}")
  15. private String email;
  16. public Integer getId() {
  17. return id;
  18. }
  19. public void setId(Integer id) {
  20. this.id = id;
  21. }
  22. public String getName() {
  23. return name;
  24. }
  25. public void setName(String name) {
  26. this.name = name;
  27. }
  28. public String getEmail() {
  29. return email;
  30. }
  31. public void setEmail(String email) {
  32. this.email = email;
  33. }
  34. @Override
  35. public String toString() {
  36. return "Person{" +
  37. "id=" + id +
  38. ", name='" + name + '\'' +
  39. ", email='" + email + '\'' +
  40. '}';
  41. }
  42. }

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

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

发表评论

表情:
评论列表 (有 0 条评论,345人围观)

还没有评论,来说两句吧...

相关阅读