Spring注解驱动开发第19讲——使用@PropertySource加载配置文件,我只看这一篇!!
发布日期:2021-06-30 17:56:08 浏览次数:2 分类:技术文章

本文共 4541 字,大约阅读时间需要 15 分钟。

简单介绍一下@PropertySource和@PropertySources这俩注解

@PropertySource注解概述

@PropertySource注解是Spring 3.1开始引入的配置类注解。通过@PropertySource注解可以将properties配置文件中的key/value存储到Spring的Environment中,Environment接口提供了方法去读取配置文件中的值,参数是properties配置文件中定义的key值。当然了,也可以使用@Value注解用${}占位符为bean的属性注入值。

我们来看一下@PropertySource注解的源代码,如下所示。

在这里插入图片描述
从@PropertySource的源码中可以看出,我们可以通过@PropertySource注解指定多个properties文件,使用的形式如下所示。

@PropertySource(value={
"classpath:/person.properties", "classpath:/car.properties"})

细心的读者可以看到,在@PropertySource注解的上面标注了如下的注解信息。

@Repeatable(PropertySources.class)

看到这里,小伙伴们是不是有种恍然大悟的感觉呢?没错,我们也可以使用@PropertySources注解来指定properties配置文件。

@PropertySources注解概述

首先,我们也来看下@PropertySources注解的源码,如下所示。

在这里插入图片描述
@PropertySources注解的源码比较简单,只有一个PropertySource[]数组类型的value属性,那我们如何使用@PropertySources注解指定配置文件呢?其实也很简单,使用如下所示的方式就可以了。

@PropertySources(value={
@PropertySource(value={
"classpath:/person.properties"}), @PropertySource(value={
"classpath:/car.properties"}),})

是不是很简单呢?接下来,我们就以一个小案例来说明@PropertySource注解的用法。

一个小案例来说明@PropertySource注解的用法

准备工作

首先,我们在工程的src/main/resources目录下创建一个配置文件,例如person.properties,该文件的内容如下所示。

person.nickName=小甜甜

然后,我们在Person类中新增一个nickName字段,如下所示。

package com.meimeixia.bean;import org.springframework.beans.factory.annotation.Value;public class Person {
@Value("李阿昀") private String name; @Value("#{20-2}") private Integer age; private String nickName; // 昵称 public String getNickName() {
return nickName; } public void setNickName(String nickName) {
this.nickName = nickName; } 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 Person(String name, Integer age) {
super(); this.name = name; this.age = age; } public Person() {
super(); // TODO Auto-generated constructor stub } @Override public String toString() {
return "Person [name=" + name + ", age=" + age + ", nickName=" + nickName + "]"; } }

目前,我们并没有为Person类的nickName字段赋值,所以,此时Person类的nickName字段的值为空。我们可以运行IOCTest_PropertyValue类中的test01()方法来看下输出结果,如下所示。

在这里插入图片描述
可以看到,Person类的nickName字段的值确实输出了null。

使用XML配置文件方式获取值

如果我们需要在XML配置文件中获取person.properties文件中的值,那么我们首先需要在Spring的XML配置文件中引入context名称空间,并且使用context命名空间导入person.properties文件,之后在bean的属性字段中使用如下方式将person.properties文件中的值注入到Person类的nickName字段上。

此时,整个beans.xml文件的内容如下所示。

这样就可以将person.properties文件中的值注入到Person类的nickName字段上了。

然后,我们在IOCTest_PropertyValue类中创建一个test02()测试方法,如下所示。

@Testpublic void test02() {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:beans.xml"); Person person = (Person) applicationContext.getBean("person"); System.out.println(person);}

接着,运行以上test02()方法,输出的结果信息如下所示。

在这里插入图片描述

使用注解方式获取值

如果我们使用注解的方式,那么该如何做呢?首先,我们需要在MainConfigOfPropertyValues配置类上添加一个@PropertySource注解,如下所示。

package com.meimeixia.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;import com.meimeixia.bean.Person;// 使用@PropertySource读取外部配置文件中的key/value保存到运行的环境变量中,加载完外部的配置文件以后,使用${}取出配置文件中的值@PropertySource(value={
"classpath:/person.properties"})@Configurationpublic class MainConfigOfPropertyValues {
@Bean public Person person() {
return new Person(); } }

这里使用的@PropertySource(value={"classpath:/person.properties"})注解就相当于XML配置文件中使用的<context:property-placeholder location="classpath:person.properties" />

然后,我们就可以在Person类的nickName字段上使用@Value注解来获取person.properties文件中的值了,如下所示。

@Value("${person.nickName}")private String nickName; // 昵称

配置完成后,我们再次运行IOCTest_PropertyValue类中的test01()方法来看下输出结果,如下所示。

在这里插入图片描述
可以看到,此时Person类的nickName字段已经注入小甜甜这个值了。

使用Environment获取值

上面我已经说过,使用@PropertySource注解读取外部配置文件中的key/value之后,是将其保存到运行的环境变量中了,所以我们也可以通过运行环境来获取外部配置文件中的值。

这里,我们可以稍微修改一下IOCTest_PropertyValue类中的test01()方法,即在其中添加一段使用Environment获取person.properties文件中的值的代码,如下所示。

@Testpublic void test01() {
printBeans(applicationContext); System.out.println("==================="); Person person = (Person) applicationContext.getBean("person"); System.out.println(person); ConfigurableEnvironment environment = applicationContext.getEnvironment(); String property = environment.getProperty("person.nickName"); System.out.println(property); // 关闭容器 applicationContext.close();}

运行以上test01()方法,可以看到输出的结果信息如下所示。

在这里插入图片描述
可以看到,使用Environment确实能够获取到person.properties文件中的值。

转载地址:https://liayun.blog.csdn.net/article/details/110485086 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Spring注解驱动开发第20讲——使用@Autowired、@Qualifier、@Primary这三大注解自动装配组件,你会了吗?
下一篇:Spring注解驱动开发第18讲——如何使用@Value注解为bean的属性赋值呢?

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月22日 06时25分29秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章

【深度学习笔记】循环神经网络和递归神经网络区别 2019-04-30
【学习笔记】英文科技论文常见英语句式积累 2019-04-30
【深度学习笔记】PixelShuffle 2019-04-30
【python3学习笔记】斜杠和双斜杠运算符的区别 2019-04-30
【深度学习笔记】torch.nn.Sequential(* args) 与 torch.nn.Module 2019-04-30
【深度学习笔记】用torch.nn.Sequential()搭建神经网络模型 2019-04-30
【深度学习笔记】用torch.nn.ModuleList搭建神经网络 2019-04-30
【解决错误】AttributeError: module ‘scipy.misc‘ has no attribute ‘imread‘ 2019-04-30
【解决错误】复现RCAN的时候遇到了ImportError: cannot import name ‘_update_worker_pids’ from ‘torch._C’ 2019-04-30
【解决错误】ModuleNotFoundError: No module named ‘skimage‘ 2019-04-30
【深度学习笔记】pytorch的点乘(dot product) 2019-04-30
【深度学习笔记】残差 2019-04-30
【错误解决】cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\imgproc\sr 2019-04-30
【python学习笔记】读取指定文件夹中的图片,结合边缘保留滤波EPF 2019-04-30
【工具和环境】Linux下安装pycharm 2019-04-30
【Accumulation】The last two sentences of the abstract 2019-04-30
【Accumulation】The definition of SISR 2019-04-30
【工具与环境】Windows下安装Sublime Text 3 2019-04-30
【解决错误】ValueError: some of the strides of a given numpy array are negative. 2019-04-30
【工具与环境】Excel中批量插入行 2019-04-30