声明配置类--- //使用@PropertySource读取外部配置文件中的k/v保存到运行的环境变量中;加载完外部的配置文件以后使用${}取出配置文件的值 @PropertySource(value={"classpath:/person.properties"}) @Configuration
1.定义person实体类,使用@Value方式注入,取出配置文件中的值
//使用@Value赋值; //1、基本数值 //2、可以写SpEL; #{} //3、可以写${};取出配置文件【properties】中的值(在运行环境变量里面的值) @Value("张三") private String name; @Value("#{20-2}") private Integer age; @Value("${person.nickName}") private String nickName;
2,也可以通过获取容器的环境变量,获取
ConfigurableEnvironment environment = applicationContext.getEnvironment(); String property = environment.getProperty("person.nickName");