当前位置: 首页 > news >正文

Spring中的@Value注解详解

Spring中的@Value注解详解

概述

本文配置文件为yml文件

在使用spring框架的项目中,@Value是经常使用的注解之一。其功能是将与配置文件中的键对应的值分配给其带注解的属性。在日常使用中,我们常用的功能相对简单。本文使您系统地了解@Value的用法。

@Value 注解可以用来将外部的值动态注入到 Bean 中,在 @Value 注解中,可以使${} 与 #{} ,它们的区别如下:

(1)@Value(“${}”):可以获取对应属性文件中定义的属性值。
(2)@Value(“#{}”):表示 SpEl 表达式通常用来获取 bean 的属性,或者调用 bean 的某个方法。

使用方式

根据注入的内容来源,@ Value属性注入功能可以分为两种:通过配置文件进行属性注入和通过非配置文件进行属性注入。
非配置文件注入的类型如下:

  1. 注入普通字符串
  2. 注入操作系统属性
  3. 注入表达式结果
  4. 注入其他bean属性
  5. 注入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框架的项目中&#xff0c;Value是经常使用的注解之一。其功能是将与配置文件中的键对应的值分配给其带注解的属性。在日常使用中&#xff0c;我们常用的功能相对简单。本文使您系统地了解Value的用法。 Value…...

YSL赢麻了?SMI社媒心智品牌榜Top20公布:YSL破局夺魁,国货品牌现后起之秀

全文速览 1.数说故事联合用户说从美妆、彩妆、护肤三板块全新发布《SMI社媒心智品牌榜》。 2.圣罗兰、兰蔻、欧莱雅等法国高端美妆大牌垄断美妆《SMI社媒心智品牌榜》前三甲。 3.彩妆Top20榜单中&#xff0c;底妆产品稳居前列&#xff0c;色彩美妆占据一席之地。 4.护肤TOP…...

链式哈希,一致性哈希,倒排表

在普通的查询中&#xff0c;通过关键码的比较进行查找&#xff0c;而哈希是根据关键码直接定位到数据项 哈希冲突&#xff1a;同一个关键码经过哈希函数后指向同一个记录集 链式哈希 using namespace std; #define M 13 typedef int KeyType; //typedef struct //{ // KeyTyp…...

Python操作XML教程:读取、写入、修改和保存XML文档

目录 导入所需模块解析XML文档获取元素遍历XML文档写入新的元素修改元素的内容和属性删除元素保存修改后的XML文档示例演示python操作xml的常用方法 XML是一种常见的数据交换格式&#xff0c;在许多应用中都被广泛使用。通过掌握Python操作XML的基础知识&#xff0c;您将能够轻…...

Oracle数据库中了locked1勒索病毒,用友nchome配置文件损坏该如何解除

随着互联网技术的不断发展&#xff0c;网络安全问题也越来越受到人们的关注。其中&#xff0c;勒索病毒是一种比较常见的网络安全威胁。最近很多集团企业在使用Oracle数据库的过程中&#xff0c;遭遇到了locked1勒索病毒的攻击&#xff0c;导致企业的用友nchome配置文件损坏&am…...

leecode 数据库: 602. 好友申请 II :谁有最多的好友

数据导入&#xff1a; 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是一个流行的开源监控系统&#xff0c;它可以帮助我们收集、存储和查询应用程序或系统的时间序列数据。在使用Prometheus进行监控时&#xff0c;通常需要根据服务水平指标&#xff08;Service Level Objectives&#xff0c;简称SLO&#xff09;来设置告警规则。 SLO…...

调用百度API实现图像风格转换

目录 1、作者介绍2、基本概念2.1 人工智能云服务与百度智能云2.2 图像风格转换 3、调用百度API实现图像风格转换3.1 配置百度智能云平台3.2 环境配置3.3 完整代码实现3.4 效果展示3.5 问题与分析 1、作者介绍 张元帮&#xff0c;男&#xff0c;西安工程大学电子信息学院&#…...

5个最好的WooCommerce商城自动化动作来增加销售量

您是否正在寻找简单智能的方法来自动执行任务并增加 WooCommerce 商店的销售额&#xff1f; 通过在线商店中的自动化任务&#xff0c;您可以在发展业务和增加销售额的同时节省时间和金钱。 在本文中&#xff0c;我们将向您展示如何使用 WooCommerce商城自动化来增加销售额。 …...

打开数据结构大门——实现小小顺序表

文章目录 前言顺序表的概念及分类搭建项目&#xff08;Seqlist&#xff09;:apple:搭建一个顺序表结构&&定义所需头文件&&函数:banana:初始化:pear:打印:watermelon:数据个数:smile:检查容量:fireworks:判空:tea:在尾部插入数据:tomato:在尾部删除数据:lemon:在…...

一.RxJava

1.RxJava使用场景 RxJava核心思想 Rx思维:响应式编程,从起点到终点,中途不能断掉,并且可以在中途添加拦截. 生活中的例子: 起点(分发事件,我饿了)->下楼->去餐厅->点餐->终点(吃饭,消费事件) 程序中的例子: 起点(分发事件,点击登录)->登录API->请求服务器-…...

如何使用 VSCode 软件运行C代码

VSCode 的下载和扩展的配置可以参考文章&#xff1a;VSCode 的安装与插件配置。 VSCode 是很好用的编辑器&#xff0c;通过给其配置 MinGW-w64 插件就可以在它上面编译运行C代码了。 在没有配置 MinGW-w64 插件时&#xff0c;在 VSCode 中运行下面的代码后打印如下图所示。 这…...

C# 调用Matlab打包的 DLL文件(傻瓜式操作)

1、准备Matlab代码 2. 打包 在matlab命令行窗口输入deploytool,打开MATLAB Complier,选择Library Compiler 在TYPE中选择.NET Assembly;在EXPORTED FUNCTIONS中选择要打包的文件&#xff1b;可以选择为自己打包的文件自定义NameSpace名称&#xff0c;本例中将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 二、核心代码&#xff08;一&#xff09;逻辑层index.js&#xff08;二&#xff09;渲染层…...

【面试题】中高级前端工程师都需要熟悉的技能--前端缓存

前端缓存 一、前言二、web缓存分类1. HTTP缓存&#xff1a;2. 浏览器缓存&#xff1a;3. Service Worker&#xff1a;4. Web Storage缓存&#xff1a;5. 内存缓存&#xff1a; 三、http缓存详解1、http缓存类型a. 基于有效时间的缓存控制&#xff1a;b. 基于资源标识的缓存&…...

小红书数据分析:首播卖6亿,小红书直播开启新纪元!

5月22日&#xff0c;章小蕙在小红书开启了第一场带货直播。继董洁之后&#xff0c;小红书又迎来一位超级带货KOL。 据千瓜数据显示&#xff0c;相关话题#章小蕙小红书直播#上线不到30天&#xff0c;话题浏览量就高达2814.89万&#xff0c;笔记互动量达22.24万。 图 | 千瓜数据…...

Weex中,关于组件的水平排列竖直排列居中对齐居左对齐居右对齐低部对齐顶部对齐布局对齐说明

容器内子组件排列方向 子组件竖直方向排列&#xff08;默认&#xff09; 子组件水平方向排列 <style> .container {flex-direction: row;direction: ltr; } </style>子组件在父组件容器中的对齐方式 我们主要使用两个属性实现子组件在父组件的对齐方式&#xff…...

服务(第二十八篇)rsync

配置rsync源服务器&#xff1a; #建立/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 的功能和行为&#xff0c;并且可以在多个组件之间共享代码和逻辑。插件可以用于添加全局组件、指令、混入、过滤器等&#xff0c;并且可以在应用程序启动时自动安装。 1. 创建插件 创建插件需要…...

Android 系统内的守护进程 - main类服务(3) : installd

声明 只要是操作系统,不用说的就是其中肯定会运行着一些很多守护进程(daemon)来完成很多杂乱的工作。通过系统中的init.rc文件也可以看出来,其中每个service中就包含着系统后台服务进程。而这些服务被分为:core类服务(adbd/servicemanager/healthd/lmkd/logd/vold)和mai…...

React 第五十五节 Router 中 useAsyncError的使用详解

前言 useAsyncError 是 React Router v6.4 引入的一个钩子&#xff0c;用于处理异步操作&#xff08;如数据加载&#xff09;中的错误。下面我将详细解释其用途并提供代码示例。 一、useAsyncError 用途 处理异步错误&#xff1a;捕获在 loader 或 action 中发生的异步错误替…...

使用VSCode开发Django指南

使用VSCode开发Django指南 一、概述 Django 是一个高级 Python 框架&#xff0c;专为快速、安全和可扩展的 Web 开发而设计。Django 包含对 URL 路由、页面模板和数据处理的丰富支持。 本文将创建一个简单的 Django 应用&#xff0c;其中包含三个使用通用基本模板的页面。在此…...

关于iview组件中使用 table , 绑定序号分页后序号从1开始的解决方案

问题描述&#xff1a;iview使用table 中type: "index",分页之后 &#xff0c;索引还是从1开始&#xff0c;试过绑定后台返回数据的id, 这种方法可行&#xff0c;就是后台返回数据的每个页面id都不完全是按照从1开始的升序&#xff0c;因此百度了下&#xff0c;找到了…...

【Go语言基础【13】】函数、闭包、方法

文章目录 零、概述一、函数基础1、函数基础概念2、参数传递机制3、返回值特性3.1. 多返回值3.2. 命名返回值3.3. 错误处理 二、函数类型与高阶函数1. 函数类型定义2. 高阶函数&#xff08;函数作为参数、返回值&#xff09; 三、匿名函数与闭包1. 匿名函数&#xff08;Lambda函…...

Java毕业设计:WML信息查询与后端信息发布系统开发

JAVAWML信息查询与后端信息发布系统实现 一、系统概述 本系统基于Java和WML(无线标记语言)技术开发&#xff0c;实现了移动设备上的信息查询与后端信息发布功能。系统采用B/S架构&#xff0c;服务器端使用Java Servlet处理请求&#xff0c;数据库采用MySQL存储信息&#xff0…...

SQL慢可能是触发了ring buffer

简介 最近在进行 postgresql 性能排查的时候,发现 PG 在某一个时间并行执行的 SQL 变得特别慢。最后通过监控监观察到并行发起得时间 buffers_alloc 就急速上升,且低水位伴随在整个慢 SQL,一直是 buferIO 的等待事件,此时也没有其他会话的争抢。SQL 虽然不是高效 SQL ,但…...

【JVM面试篇】高频八股汇总——类加载和类加载器

目录 1. 讲一下类加载过程&#xff1f; 2. Java创建对象的过程&#xff1f; 3. 对象的生命周期&#xff1f; 4. 类加载器有哪些&#xff1f; 5. 双亲委派模型的作用&#xff08;好处&#xff09;&#xff1f; 6. 讲一下类的加载和双亲委派原则&#xff1f; 7. 双亲委派模…...

FFmpeg avformat_open_input函数分析

函数内部的总体流程如下&#xff1a; avformat_open_input 精简后的代码如下&#xff1a; int avformat_open_input(AVFormatContext **ps, const char *filename,ff_const59 AVInputFormat *fmt, AVDictionary **options) {AVFormatContext *s *ps;int i, ret 0;AVDictio…...

Linux入门(十五)安装java安装tomcat安装dotnet安装mysql

安装java yum install java-17-openjdk-devel查找安装地址 update-alternatives --config java设置环境变量 vi /etc/profile #在文档后面追加 JAVA_HOME"通过查找安装地址命令显示的路径" #注意一定要加$PATH不然路径就只剩下新加的路径了&#xff0c;系统很多命…...

Qt学习及使用_第1部分_认识Qt---Qt开发基本流程

前言 学以致用,通过QT框架的学习,一边实践,一边探索编程的方方面面. 参考书:<Qt 6 C开发指南>(以下称"本书") 标识说明:概念用粗体倾斜.重点内容用(加粗黑体)---重点内容(红字)---重点内容(加粗红字), 本书原话内容用深蓝色标识,比较重要的内容用加粗倾…...