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();
}