spring 注解学习 三 spring属性值的注入
一、属性值的注入
1、基本数值
2、可以写SpEL; #{}
public class Person {
@Value("张三")
private String name;
@Value("#{20-2}")
private Integer age;
@Value("${person.age}")
private Integer age;
}
配置文件中的值需要加载到spring中的Environment环境变量中,spring在启动时,会把系统变量与jvm虚拟机参数都加入到Environment环境变量,如果有.properties配置文件,也会加入到Environment变量中。
载入配置文件:
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@ComponentScan("com.*")
@PropertySource(value= {"classpath:/application.properties"})
public class AppConfig {
}
手工获取参数配置
@Test
public void fun() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
ConfigurableEnvironment environment = applicationContext.getEnvironment();
System.out.println(environment);
Map<String, Object> systemProperties = environment.getSystemProperties();//获取系统变量
Map<String, Object> systemEnvironment = environment.getSystemEnvironment();//获取虚拟机参数
System.getenv();//获取系统变量
System.getProperties();//获取虚拟机参数
System.out.println(environment.getProperty("demo.value"));
System.out.println(environment.getProperty("person.name"));
System.out.println(environment.getProperty("java.runtime.version"));
System.out.println(environment.getProperty("LOCALAPPDATA"));
applicationContext.close();
}

浙公网安备 33010602011771号