Spring @value和@PropertySource註解使用方法解析
阿新 • • 發佈:2020-01-07
這篇文章主要介紹了Spring @value和@PropertySource註解使用方法解析,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
- @Value註解:可以使用注入基本字串 EL表示式,從配置檔案讀取資料
- @PropertySource用於引入單個配置檔案
- @PropertySources用於引入多個配置檔案
- @PropertySource或者@PropertySources引入的資料都是存在環境變數ConfigurableEnvironment中的
- 在resouces資料夾下新建一個cat.properties檔案,寫入內容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 } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。