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】中的值(在运行环境变量里面的值)*/
@PropertySource({"classpath:/student.properties"})//指定配置文件classPath
@Component //此时使用的是@Component方式注入,则@PropertySource放在哪都可以
public class Student {@Value("张三")//直接赋值private String name;@Value("${stu.name}")//从配置文件中取值private String alias;@Value("${os.name}")//从容器中读取环境变量private String system;@Value("#{33-12}")//使用SpEL 计算private Integer age;
//    @Value("${stu.birthDate}")//不能处理日期private Date birthDate;@Value("${stu.hasNickName}") //布尔值private Boolean hasNickName;@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", alias='" + alias + '\'' +", system='" + system + '\'' +", age=" + age +", birthDate=" + birthDate +", hasNickName=" + hasNickName +'}';}public Boolean getHasNickName() {return hasNickName;}public void setHasNickName(Boolean hasNickName) {this.hasNickName = hasNickName;}public String getAlias() {return alias;}public void setAlias(String alias) {this.alias = alias;}public String getSystem() {return system;}public void setSystem(String system) {this.system = system;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Date getBirthDate() {return birthDate;}public void setBirthDate(Date birthDate) {this.birthDate = birthDate;}
}@Configuration
@ComponentScan(basePackages = "com.java.model")
//@PropertySource({"classpath:/student.properties"}) //放在这里也可以
public class PropertyValueConfig {}public class PropertyValueTest {public static void main(String[] args) {AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(PropertyValueConfig.class);Student s = applicationContext.getBean(Student.class);System.out.println(s);}
}测试结果:
Student{name='张三', alias='张三', system='Windows 7', age=21, birthDate=null, hasNickName=true}

方式二:使用@Bean方式注入Student对象

/****  使用@Value赋值;*     1、基本数值*     2、可以写SpEL; #{}*  3、可以写${};取出配置文件【properties】中的值(在运行环境变量里面的值)*/
public class Student {@Value("张三")//直接赋值private String name;@Value("${stu.name}")//从配置文件中取值private String alias;@Value("${os.name}")//从容器中读取环境变量private String system;@Value("#{33-12}")//使用SpEL 计算private Integer age;
//    @Value("${stu.birthDate}")//不能处理日期private Date birthDate;@Value("${stu.hasNickName}") //布尔值private Boolean hasNickName;@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", alias='" + alias + '\'' +", system='" + system + '\'' +", age=" + age +", birthDate=" + birthDate +", hasNickName=" + hasNickName +'}';}public Boolean getHasNickName() {return hasNickName;}public void setHasNickName(Boolean hasNickName) {this.hasNickName = hasNickName;}public String getAlias() {return alias;}public void setAlias(String alias) {this.alias = alias;}public String getSystem() {return system;}public void setSystem(String system) {this.system = system;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Date getBirthDate() {return birthDate;}public void setBirthDate(Date birthDate) {this.birthDate = birthDate;}
}@Configuration
@PropertySource({"classpath:/student.properties"}) //此时只能放在这里加载
public class PropertyValueConfig {@Beanpublic Student student(){return new Student();}
}public class PropertyValueTest {public static void main(String[] args) {AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(PropertyValueConfig.class);Student s = applicationContext.getBean(Student.class);System.out.println(s);}
}测试结果:
Student{name='张三', alias='张三', system='Windows 7', age=21, birthDate=null, hasNickName=true}

3.EmbeddedValueResolverAware方式实现和@Value一样的效果

EmbeddedValueResolverAware是一个String型的value解析器,想要通过这个获取值的任何对象,都可以实现这个接口。

/*** Interface to be implemented by any object that wishes to be notified of a* {@code StringValueResolver} for the resolution of embedded definition values.** <p>This is an alternative to a full ConfigurableBeanFactory dependency via the* {@code ApplicationContextAware}/{@code BeanFactoryAware} interfaces.** @author Juergen Hoeller* @author Chris Beams* @since 3.0.3* @see org.springframework.beans.factory.config.ConfigurableBeanFactory#resolveEmbeddedValue(String)* @see org.springframework.beans.factory.config.ConfigurableBeanFactory#getBeanExpressionResolver()* @see org.springframework.beans.factory.config.EmbeddedValueResolver*/
public interface EmbeddedValueResolverAware extends Aware {/*** Set the StringValueResolver to use for resolving embedded definition values.*/void setEmbeddedValueResolver(StringValueResolver resolver);}

使用方法如下:

@Configuration
//@ComponentScan(basePackages = "com.java.model")
@PropertySource({"classpath:/student.properties"})//指定配置文件classPath
public class PropertyValueConfig implements EmbeddedValueResolverAware{@Beanpublic Student student(){System.out.println("EmbeddedValueResolverAware----->setEmbeddedValueResolver--->stu = "+stuName);return new Student();}private String stuName;@Overridepublic void setEmbeddedValueResolver(StringValueResolver resolver) {this.stuName = resolver.resolveStringValue("${stu.name}");}
}

【Spring注解系列12】@Value与@PropertySource注解相关推荐

  1. [Spring实战系列](13)使用注解自动装配

    1. 简介 从Spring2.5开始,我们就可以使用注解的自动装配方式装配Spring Bean的属性.使用注解自动装配方式与在XML中使用autowire属性自动装配没有太大区别.那为啥还要研发出这 ...

  2. 【Spring注解系列04】@Condition条件注解

    1.@Condition条件注解 满足指定条件,则会加载对应的实例或者类.该注解可以作用于类和方法上. @Condition类属性值中,对应的类,必须是实现Condition接口的类 2.实例 配置类 ...

  3. Spring之AOP系列--将方法上的注解做为切点(用@Around)

    原文网址:Spring之AOP系列--将方法上的注解做为切点(用@Around)_IT利刃出鞘的博客-CSDN博客 简介 说明         本文介绍Spring(SpringBoot)的AOP的用 ...

  4. Spring Boot @PropertySource注解加载指定配置文件(五)

    我们可以通过@ConfigurationProperties和@Value两个注解获取主配置文件application.properties 或 apllication.yml中的配置信息,但是如果我 ...

  5. Spring学习第6篇: 基于注解使用IOC

    大家家好,我是一名网络怪咖,北漂五年.相信大家和我一样,都有一个大厂梦,作为一名资深Java选手,深知Spring重要性,现在普遍都使用SpringBoot来开发,面试的时候SpringBoot原理也 ...

  6. Spring基础专题——第九章(基础注解编程——上)

    目标,去年一年比较懒吧,所以今年我希望我的知识可以分享给正在奋斗中的互联网开发人员,以及未来想往架构师上走的道友们我们一起进步,从一个互联网职场小白到一个沪漂湿人,一路让我知道分享是一件多么重要的事情 ...

  7. 盘点Spring Boot最核心的27个注解

    Spring Boot方式的项目开发已经逐步成为Java应用开发领域的主流框架,它不仅可以方便地创建生产级的Spring应用程序,还能轻松地通过一些注解配置与目前比较火热的微服务框架SpringClo ...

  8. spring,mybatis事务管理配置与@Transactional注解使用

    spring,mybatis事务管理配置与@Transactional注解使用 概述 事务管理对于企业应用来说是至关重要的,即使出现异常情况,它也可以保证数据的一致性. Spring Framewor ...

  9. spring mvc异常统一处理(ControllerAdvice注解)

    spring mvc异常统一处理(ControllerAdvice注解) 参考文章: (1)spring mvc异常统一处理(ControllerAdvice注解) (2)https://www.cn ...

最新文章

  1. LANMP框架搭建——源码编译
  2. C语言递归算法将十进制转换为二进制(附完整源码)
  3. ubuntu下命令安装与卸载软件方法
  4. 跟着石头哥哥学cocos2d-x(四)--cocos2dx中的动画以及TexturePacker使用
  5. jmeter 实际运行线程数达不到设定值_Jmeter技术知识-常用组件实战演示(2020年最新)...
  6. 解决Qt-至少需要一个有效且已启用的储存库 问题
  7. JY游戏开发,案例之 《下到一百层》,欢迎大家品赏。
  8. python自动化办公真的好用吗-用 Python 自动化办公,我与大神之间的差距一下就拉小了...
  9. 如果“永远”只是一瞬间
  10. 【DDD】领域驱动设计实践 —— Application层实现
  11. 微信小程序字母索引菜单
  12. excel2010将数字变成以文本存储的数字
  13. spring的 init-method和 destory-method方法
  14. Android 使用crosswalk实例
  15. 发布一款新闻资讯软件(android版)
  16. 课程设计:通讯录系统(数据库)
  17. 【坑】html5中使用canvas画圆,弧度和角度傻傻分不清楚
  18. Windows2012r2 安装SQLSERVER2017 与 SQLSERVER2016 的错误提示解决KB2919355 以及 KB2919442
  19. flink实时生产维度表
  20. RHCSA第二次作业

热门文章

  1. 单列模式(懒汉)测试代码
  2. Feature Support and Procedure Mapping
  3. AB1601 PWM模块
  4. 爬虫篇——User-Agent爬取备用及存储
  5. [Issue Fixed]-fatal: unable to access xxx: server certificate verification
  6. [armv9]-ARMV9 CCA 机密计算简介
  7. Django框架连接MySQL数据库
  8. 正则表达式,解决要么有要有没有,但必须开头
  9. 题目3:文本文件单词的检索与计数(实现代码)
  10. 2020-11-15(IEEE浮点数计算)