@Value
首先,我们可以通过注解@Value来给Bean对象的属性进行赋值,可以赋值的内容如下:
①、基本类型值
例如:
@Value("Rosie")
private String name;
②、使用Spring表达式SPEL,#{运算}
例如:
@Value("#{17 + 1}")
private Integer age;
③、使用${key名称}表达式使用外部配置文件【通常是.properties文件】中的值。
例如:
@Value("${man.nickname}")
private String nickName;
使用该方式需要提前作如下配置:
1)在配置类中,使用注解@PropertySource或@PropertySources,读取配置文件信息到运行环境对象中。(等价于普通配置中:<context:property-placeholder location="classpath:/ManPerson.properties,classpath:/WomanPerson.properties"/>)
2)使用@Value("${man.nickname}")表达式,将配置文件中的值,赋值到Bean的属性上。