Spring註解系列十八:屬性賦值-@PropertySource

1、創建配置文件person.properties

person.name=李四
person.age=20

2、使用@PropertySource讀取外部配置文件中的k/v保存到運行的環境變量中;加載完外部的配置文件以後使用${}取出配置文件的值。@PropertySource是可重複註解。也可以用@PropertySources註解指定多個PropertySource加載多個配置文件。

<context:property-placeholder location="classpath:person.properties"/>
@PropertySource(value={"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValues {
	
	@Bean
	public Person person(){
		return new Person();
	}
}

3、修改Person

//3、可以寫${};取出配置文件【properties】中的值(在運行環境變量裏面的值)
@Value("${person.name}")
private String name;
@Value("${person.age}")
private Integer age;

4、測試

@Test
public void test01(){
	AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);
	String[] definitionNames = applicationContext.getBeanDefinitionNames();
	for (String name : definitionNames) {
		System.out.println(name);
	}

	Person person = (Person) applicationContext.getBean("person");
	System.out.println(person);

	ConfigurableEnvironment environment = applicationContext.getEnvironment();
	String property = environment.getProperty("person.name");
	System.out.println(property);

	applicationContext.close();
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章