1.@Value与@PropertySource注解
@Value注解:主要用于赋值,该值可以是取值配置文件中的,也可以直接赋值,也可以使用SpEl表达式进行计算的结果,抑或直接从环境变量中获取。 该注解不能处理日期类赋值
1、基本数值
2、可以写SpEL; #{}
3、可以写${};取出配置文件【properties】中的值(在运行环境变量里面的值)
原理是底层使用了后置处理器AutowiredAnnotationBeanPostProcessor。
* <p>Note that actual processing of the {@code @Value} annotation is performed
* by a {@link org.springframework.beans.factory.config.BeanPostProcessor
* BeanPostProcessor} which in turn means that you <em>cannot</em> use
* {@code @Value} within
* {@link org.springframework.beans.factory.config.BeanPostProcessor
* BeanPostProcessor} or
* {@link org.springframework.beans.factory.config.BeanFactoryPostProcessor BeanFactoryPostProcessor}
* types. Please consult the javadoc for the {@link AutowiredAnnotationBeanPostProcessor}
* class (which, by default, checks for the presence of this annotation).
@PropertySource注解:主要用于加载配置文件,value值为classpath
等价于 <context:property-placeholder location="classpath:student.properties"/>
2.实例
@PropertySource放置的位置问题:
1.若使用@Component方式注入对象,则@PropertySource防止在普通类Student或配置类中都可以
2.若使用@Bean方式注入Student对象,则@PropertySource必须放在配置类上加载
方式一:使用@Component方式注入Student对象
/**
*
* 使用@Value赋值;
* 1、基本数值
* 2、可以写SpEL; #{}
* 3、可以写${};取出配置文件【properties】中的值(在运行环境变量