【Spring注解系列12】@Value与@PropertySource注解

本文详细介绍了Spring框架中的@Value和@PropertySource注解,@Value用于从配置文件、环境变量中获取值,支持SpEL表达式;@PropertySource用于加载配置文件。同时,文章探讨了@PropertySource的使用位置以及@Component与@Bean注解下不同加载方式。最后,文章提到了通过实现EmbeddedValueResolverAware接口来达到与@Value相同的效果。
摘要由CSDN通过智能技术生成

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】中的值(在运行环境变量
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值