溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

@value和@PropertySource注解怎么在Spring中使用

發(fā)布時間:2021-03-23 15:01:45 來源:億速云 閱讀:195 作者:Leah 欄目:編程語言

本篇文章給大家分享的是有關(guān)@value和@PropertySource注解怎么在Spring中使用,小編覺得挺實用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

  • @Value注解:可以使用注入基本字符串 EL表達式,從配置文件讀取數(shù)據(jù)

  • @PropertySource用于引入單個配置文件

  • @PropertySources用于引入多個配置文件

  • @PropertySource或者@PropertySources引入的數(shù)據(jù)都是存在環(huán)境變量ConfigurableEnvironment中的

  • 在resouces文件夾下新建一個cat.properties文件,寫入內(nèi)容parent=tiger

public class Cat {
  @Value("貓") //直接注入字符串
  private String name;
  @Value("#{12+2}") //支持EL表達式
  private int age;
  @Value("${parent}") //支持配置文件讀取
  private String parent;
  public Cat() {
    System.out.println("貓被初始化");
  }

  @Override
  public String toString() {
    return "Cat{" +
        "name='" + name + '\'' +
        ", age=" + age +
        ", parent='" + parent + '\'' +
        '}';
  }
}
@Import({Cat.class})
@PropertySources({@PropertySource(value ="cat.properties")})
public class Appconfig {
}
public class Demo {
  public static void main(String[] args) {

    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Appconfig.class);
    Cat bean = context.getBean(Cat.class);
    System.out.println(bean); //Cat{name='貓', age=14, parent='tiger'}
    ConfigurableEnvironment environment = context.getEnvironment();
    System.out.println(environment.getProperty("parent")); //tiger


  }
}

@value和@PropertySource注解怎么在Spring中使用

以上就是@value和@PropertySource注解怎么在Spring中使用,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI