Spring中的@Value注解详解
Spring中的@Value注解详解
概述
本文配置文件为yml文件
在使用spring框架的项目中,@Value是经常使用的注解之一。其功能是将与配置文件中的键对应的值分配给其带注解的属性。在日常使用中,我们常用的功能相对简单。本文使您系统地了解@Value的用法。
@Value 注解可以用来将外部的值动态注入到 Bean 中,在 @Value 注解中,可以使${} 与 #{} ,它们的区别如下:
(1)@Value(“${}”):可以获取对应属性文件中定义的属性值。
(2)@Value(“#{}”):表示 SpEl 表达式通常用来获取 bean 的属性,或者调用 bean 的某个方法。
使用方式
根据注入的内容来源,@ Value属性注入功能可以分为两种:通过配置文件进行属性注入和通过非配置文件进行属性注入。
非配置文件注入的类型如下:
- 注入普通字符串
- 注入操作系统属性
- 注入表达式结果
- 注入其他bean属性
- 注入URL资源
基于配置文件的注入
首先,让我们看一下配置文件中的数据注入,无论它是默认加载的application.yml还是自定义my.yml文档(需要@PropertySource额外加载)。
application.yml文件配置,获得里面配置的端口号

程序源代码
package cn.wideth.controller;import cn.wideth.PdaAndIpadApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)
@SpringBootTest()
@ContextConfiguration(classes = PdaAndIpadApplication.class)
public class ValueController {/***Get in application.yml*/@Value("${server.port}")private String port;@Testpublic void getPort(){System.out.println(port);}
}
程序结果

自定义yml文件,application-config.yml文件配置,获得里面配置的用户密码值
注意,如果想导入自定义的yml配置文件,应该首先把自定义文件在application.yml文件中进行注册,自定义的yml文件要以application开头,形式为application-fileName

配置信息

测试程序
package cn.wideth.controller;import cn.wideth.PdaAndIpadApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)
@SpringBootTest()
@ContextConfiguration(classes = PdaAndIpadApplication.class)
public class ValueController {/***Get in application-config.yml*/@Value("${user.password}")private String password;@Testpublic void getPassword(){System.out.println(password);}
}
程序结果

基于配置文件一次注入多个值
配置信息

测试程序
package cn.wideth.controller;import cn.wideth.PdaAndIpadApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;import java.util.List;@RunWith(SpringRunner.class)
@SpringBootTest()
@ContextConfiguration(classes = PdaAndIpadApplication.class)
public class ValueController {/***Injection array (automatically split according to ",")*/@Value("${tools}")private String[] toolArray;/***Injection list form (automatic segmentation based on "," and)*/@Value("${tools}")private List<String> toolList;@Testpublic void getTools(){System.out.println(toolArray);System.out.println(toolList);}
}
程序结果

基于非配置文件的注入
在使用示例说明基于非配置文件注入属性的实例之前,让我们看一下SpEl。
Spring Expression Language是Spring表达式语言,可以在运行时查询和操作数据。使用#{…}作为操作符号,大括号中的所有字符均视为SpEl。
让我们看一下特定实例场景的应用:
注入普通字符串
测试程序
package cn.wideth.controller;import cn.wideth.PdaAndIpadApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;import java.util.List;@RunWith(SpringRunner.class)
@SpringBootTest()
@ContextConfiguration(classes = PdaAndIpadApplication.class)
public class ValueController {// 直接将字符串赋值给 str 属性@Value("hello world")private String str;@Testpublic void getValue(){System.out.println(str);}
}
程序结果

注入操作系统属性
可以利用 @Value 注入操作系统属性。
测试程序
package cn.wideth.controller;import cn.wideth.PdaAndIpadApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)
@SpringBootTest()
@ContextConfiguration(classes = PdaAndIpadApplication.class)
public class ValueController {@Value("#{systemProperties['os.name']}")private String osName; // 结果:Windows 10@Testpublic void getValue(){System.out.println(osName);}
}
程序结果

注入表达式结果
在 @Value 中,允许我们使用表达式,然后自动计算表达式的结果。将结果复制给指定的变量。如下
测试程序
package cn.wideth.controller;import cn.wideth.PdaAndIpadApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)
@SpringBootTest()
@ContextConfiguration(classes = PdaAndIpadApplication.class)
public class ValueController {// 生成一个随机数@Value("#{ T(java.lang.Math).random() * 1000.0 }")private double randomNumber;@Testpublic void getValue(){System.out.println(randomNumber);}
}
程序结果

注入其他bean属性
其他Bean
package cn.wideth.controller;import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;//其他bean,自定义名称为 myBeans
@Component("myBeans")
public class OtherBean {@Value("OtherBean的NAME属性")private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}
}
测试程序
package cn.wideth.controller;import cn.wideth.PdaAndIpadApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)
@SpringBootTest()
@ContextConfiguration(classes = PdaAndIpadApplication.class)
public class ValueController {@Value("#{myBeans.name}")private String fromAnotherBean;@Testpublic void getValue(){System.out.println(fromAnotherBean);}
}
程序结果

注入URL资源
测试程序
package cn.wideth.controller;import cn.wideth.PdaAndIpadApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import java.net.URL;@RunWith(SpringRunner.class)
@SpringBootTest()
@ContextConfiguration(classes = PdaAndIpadApplication.class)
public class ValueController {/***注入 URL 资源*/@Value("https://www.baidu.com/")private URL homePage;@Testpublic void getValue(){System.out.println(homePage);}
}
程序结果

相关文章:
Spring中的@Value注解详解
Spring中的Value注解详解 概述 本文配置文件为yml文件 在使用spring框架的项目中,Value是经常使用的注解之一。其功能是将与配置文件中的键对应的值分配给其带注解的属性。在日常使用中,我们常用的功能相对简单。本文使您系统地了解Value的用法。 Value…...
YSL赢麻了?SMI社媒心智品牌榜Top20公布:YSL破局夺魁,国货品牌现后起之秀
全文速览 1.数说故事联合用户说从美妆、彩妆、护肤三板块全新发布《SMI社媒心智品牌榜》。 2.圣罗兰、兰蔻、欧莱雅等法国高端美妆大牌垄断美妆《SMI社媒心智品牌榜》前三甲。 3.彩妆Top20榜单中,底妆产品稳居前列,色彩美妆占据一席之地。 4.护肤TOP…...
链式哈希,一致性哈希,倒排表
在普通的查询中,通过关键码的比较进行查找,而哈希是根据关键码直接定位到数据项 哈希冲突:同一个关键码经过哈希函数后指向同一个记录集 链式哈希 using namespace std; #define M 13 typedef int KeyType; //typedef struct //{ // KeyTyp…...
Python操作XML教程:读取、写入、修改和保存XML文档
目录 导入所需模块解析XML文档获取元素遍历XML文档写入新的元素修改元素的内容和属性删除元素保存修改后的XML文档示例演示python操作xml的常用方法 XML是一种常见的数据交换格式,在许多应用中都被广泛使用。通过掌握Python操作XML的基础知识,您将能够轻…...
Oracle数据库中了locked1勒索病毒,用友nchome配置文件损坏该如何解除
随着互联网技术的不断发展,网络安全问题也越来越受到人们的关注。其中,勒索病毒是一种比较常见的网络安全威胁。最近很多集团企业在使用Oracle数据库的过程中,遭遇到了locked1勒索病毒的攻击,导致企业的用友nchome配置文件损坏&am…...
leecode 数据库: 602. 好友申请 II :谁有最多的好友
数据导入: Create table If Not Exists RequestAccepted (requester_id int not null, accepter_id int null, accept_date date null); Truncate table RequestAccepted; insert into RequestAccepted (requester_id, accepter_id, accept_date) values (1, 2, 20…...
基于 Prometheus 的 SLO告警实战
Prometheus是一个流行的开源监控系统,它可以帮助我们收集、存储和查询应用程序或系统的时间序列数据。在使用Prometheus进行监控时,通常需要根据服务水平指标(Service Level Objectives,简称SLO)来设置告警规则。 SLO…...
调用百度API实现图像风格转换
目录 1、作者介绍2、基本概念2.1 人工智能云服务与百度智能云2.2 图像风格转换 3、调用百度API实现图像风格转换3.1 配置百度智能云平台3.2 环境配置3.3 完整代码实现3.4 效果展示3.5 问题与分析 1、作者介绍 张元帮,男,西安工程大学电子信息学院&#…...
5个最好的WooCommerce商城自动化动作来增加销售量
您是否正在寻找简单智能的方法来自动执行任务并增加 WooCommerce 商店的销售额? 通过在线商店中的自动化任务,您可以在发展业务和增加销售额的同时节省时间和金钱。 在本文中,我们将向您展示如何使用 WooCommerce商城自动化来增加销售额。 …...
打开数据结构大门——实现小小顺序表
文章目录 前言顺序表的概念及分类搭建项目(Seqlist):apple:搭建一个顺序表结构&&定义所需头文件&&函数:banana:初始化:pear:打印:watermelon:数据个数:smile:检查容量:fireworks:判空:tea:在尾部插入数据:tomato:在尾部删除数据:lemon:在…...
一.RxJava
1.RxJava使用场景 RxJava核心思想 Rx思维:响应式编程,从起点到终点,中途不能断掉,并且可以在中途添加拦截. 生活中的例子: 起点(分发事件,我饿了)->下楼->去餐厅->点餐->终点(吃饭,消费事件) 程序中的例子: 起点(分发事件,点击登录)->登录API->请求服务器-…...
如何使用 VSCode 软件运行C代码
VSCode 的下载和扩展的配置可以参考文章:VSCode 的安装与插件配置。 VSCode 是很好用的编辑器,通过给其配置 MinGW-w64 插件就可以在它上面编译运行C代码了。 在没有配置 MinGW-w64 插件时,在 VSCode 中运行下面的代码后打印如下图所示。 这…...
C# 调用Matlab打包的 DLL文件(傻瓜式操作)
1、准备Matlab代码 2. 打包 在matlab命令行窗口输入deploytool,打开MATLAB Complier,选择Library Compiler 在TYPE中选择.NET Assembly;在EXPORTED FUNCTIONS中选择要打包的文件;可以选择为自己打包的文件自定义NameSpace名称,本例中将NameSpace定义为…...
微信小程序学习实录3(环境部署、百度地图微信小程序、单击更换图标、弹窗信息、导航、支持腾讯百度高德地图调起)
百度地图微信小程序 一、环境部署1.need to be declared in the requiredPrivateInfos2.api.map.baidu.com 不在以下 request 合法域名3.width and heigth of marker id 9 are required 二、核心代码(一)逻辑层index.js(二)渲染层…...
【面试题】中高级前端工程师都需要熟悉的技能--前端缓存
前端缓存 一、前言二、web缓存分类1. HTTP缓存:2. 浏览器缓存:3. Service Worker:4. Web Storage缓存:5. 内存缓存: 三、http缓存详解1、http缓存类型a. 基于有效时间的缓存控制:b. 基于资源标识的缓存&…...
小红书数据分析:首播卖6亿,小红书直播开启新纪元!
5月22日,章小蕙在小红书开启了第一场带货直播。继董洁之后,小红书又迎来一位超级带货KOL。 据千瓜数据显示,相关话题#章小蕙小红书直播#上线不到30天,话题浏览量就高达2814.89万,笔记互动量达22.24万。 图 | 千瓜数据…...
Weex中,关于组件的水平排列竖直排列居中对齐居左对齐居右对齐低部对齐顶部对齐布局对齐说明
容器内子组件排列方向 子组件竖直方向排列(默认) 子组件水平方向排列 <style> .container {flex-direction: row;direction: ltr; } </style>子组件在父组件容器中的对齐方式 我们主要使用两个属性实现子组件在父组件的对齐方式ÿ…...
服务(第二十八篇)rsync
配置rsync源服务器: #建立/etc/rsyncd.conf 配置文件 vim /etc/rsyncd.conf #添加以下配置项 uid root gid root use chroot yes #禁锢在源目录 address 192.168.80.10 …...
Vue 3 第二十五章:插件(Plugins)
文章目录 1. 创建插件2. 使用插件3. 插件选项 Vue 3 的插件系统允许我们扩展 Vue 的功能和行为,并且可以在多个组件之间共享代码和逻辑。插件可以用于添加全局组件、指令、混入、过滤器等,并且可以在应用程序启动时自动安装。 1. 创建插件 创建插件需要…...
Android 系统内的守护进程 - main类服务(3) : installd
声明 只要是操作系统,不用说的就是其中肯定会运行着一些很多守护进程(daemon)来完成很多杂乱的工作。通过系统中的init.rc文件也可以看出来,其中每个service中就包含着系统后台服务进程。而这些服务被分为:core类服务(adbd/servicemanager/healthd/lmkd/logd/vold)和mai…...
基于stm32的通信系统,sim800c与服务器通信,无线通信监测,远程定位,服务器通信系统...
基于stm32的通信系统,sim800c与服务器通信,无线通信监测,远程定位,服务器通信系统,gps,sim800c,心率,温度,stm32 由STM32F103ZET6单片机核心板电路、DS18B20温度传感器电…...
res-downloader:多源媒体捕获与智能管理的跨平台资源获取工具
res-downloader:多源媒体捕获与智能管理的跨平台资源获取工具 【免费下载链接】res-downloader 视频号、小程序、抖音、快手、小红书、直播流、m3u8、酷狗、QQ音乐等常见网络资源下载! 项目地址: https://gitcode.com/GitHub_Trending/re/res-downloader 在数…...
PHP实现异步请求的四种方法
PHP中的cURL可用于发起 HTTP 请求,通常同步地等待服务器响应。如果你想要实现异步操作,即 PHP 程序继续执行而无需等待 cURL 请求完成,你可以考虑以下几种方式:使用curl_multicURL 提供了设置 curl_multi 和 curl_multi_exec 来同…...
ChampR:让每个英雄联盟玩家都能掌握专业级游戏策略
ChampR:让每个英雄联盟玩家都能掌握专业级游戏策略 【免费下载链接】champ-r 🐶 Yet another League of Legends helper 项目地址: https://gitcode.com/gh_mirrors/ch/champ-r 一、核心价值解析:ChampR如何重新定义游戏辅助工具&…...
Swagger Client 性能优化:10个技巧让你的 API 调用快如闪电
Swagger Client 性能优化:10个技巧让你的 API 调用快如闪电 【免费下载链接】swagger-js Javascript library to connect to swagger-enabled APIs via browser or nodejs 项目地址: https://gitcode.com/gh_mirrors/sw/swagger-js Swagger Client 是一款强大…...
从 MSYS2 环境中提取独立 MinGW-w64 工具链的技术方案
提取包下载:作者主页资源 一、问题背景 在配置 Windows 平台 C/C 开发环境时,开发者可能误将 MSYS2 完整环境当作 MinGW-w64 编译器套件下载安装。MSYS2 是一个集成了 Pacman 包管理器的 Unix-like 开发环境,其内部包含了完整的 MinGW-w64 工…...
SecGPT-14B提示工程:提升OpenClaw安全任务准确率的5个模板
SecGPT-14B提示工程:提升OpenClaw安全任务准确率的5个模板 1. 为什么需要专门的安全提示模板 上周我在用OpenClaw自动化处理服务器日志时,遇到了一个典型问题:当要求它"检查最近的安全事件"时,这个智能助手要么返回过…...
Qwen3.5-2B算法学习伴侣:动态图解与代码实现一键生成
Qwen3.5-2B算法学习伴侣:动态图解与代码实现一键生成 1. 算法学习的新方式 算法学习一直是开发者成长路上的必经之路,但传统的学习方式往往面临几个痛点:文字解释太抽象、静态图示不够直观、代码实现需要反复调试。Qwen3.5-2B的出现&#x…...
颠覆传统角色构建流程:Path of Building PoE2带来流放之路2效率革命
颠覆传统角色构建流程:Path of Building PoE2带来流放之路2效率革命 【免费下载链接】PathOfBuilding-PoE2 项目地址: https://gitcode.com/GitHub_Trending/pa/PathOfBuilding-PoE2 在《流放之路2》的世界里,你是否也曾经历过这些困境ÿ…...
下一代神经机器翻译质量评估框架:COMET的革命性架构与智能评估范式
下一代神经机器翻译质量评估框架:COMET的革命性架构与智能评估范式 【免费下载链接】COMET A Neural Framework for MT Evaluation 项目地址: https://gitcode.com/gh_mirrors/com/COMET COMET(A Neural Framework for MT Evaluation)…...
