首页 > 其他分享 >@value

@value

时间:2024-04-09 17:31:44浏览次数:15  
标签:Spring Value value MyComponent property my myProperty

@Value(“${xxxx}”)

@Value("${xxxx}") 是 Spring 框架中一个常见的用法,

用于,将配置属性(通常是在application.propertiesapplication.yml 文件中定义的属性)的值,注入到Spring管理的,Bean的字段、方法参数、setter方法中,

这里的 ${xxxx} 是一个占位符,它会在Spring容器启动时,被替换为 xxxx 对应的实际值。

需要注意的是

当使用 @Value("${xxxx}") 时,

如果 xxxx 在配置文件中不存在,那么默认行为是注入 null(对于对象类型)或抛出异常(对于基本类型和包装类型的原始值)。

为了避免这种情况,你可以提供一个默认值,如 @Value("${my.property:defaultValue}"),

这样当 my.property 不存在时,会注入 defaultValue。

注入到字段

	import org.springframework.beans.factory.annotation.Value;
	import org.springframework.stereotype.Component;
	  
	@Component
	public class MyComponent {
	  
		@Value("${my.property}")
		private String myProperty;
	  
		// ... 其他方法 ...  
	}

1、
	在 @Value("${my.property}") 这个注解中,
	
	"my.property" 并不是指一个名为 my 的配置文件的 property 属性,
	
	实际上,my.property 是指 Spring 配置文件(通常是 application.properties 或 application.yml)中的一个键(key)。


2、
	当 Spring 容器加载应用上下文时,它会读取这些配置文件,并将其中的键值对存储起来,
	
	然后,
	
	当 Spring 容器创建 MyComponent 的实例时,它会查找名为 my.property 的配置值,并将其注入到 myProperty 字段中。

	所以,如果您在 application.properties 文件中有以下内容:
		my.property=SomeValue
	
	那么,Spring 容器在创建 MyComponent 的实例时,会将 myProperty 字段的值设置为 SomeValue。

3、
	这里并不涉及任何名为 my 的配置文件,
	
	my.property 只是一个配置属性的键名,
	
	它可以在任何 Spring 支持的配置文件中定义,包括 application.properties、application.yml 或通过其他配置源(如环境变量、命令行参数等)定义。

4、最好,确保,您的 application.properties 或 application.yml 文件位于 Spring Boot 项目的 src/main/resources 目录下



注入到构造器参数

	import org.springframework.beans.factory.annotation.Value;  
	import org.springframework.stereotype.Component;  
	  
	@Component  
	public class MyComponent {  
	  
		private final String myProperty;  
	  
		public MyComponent(@Value("${my.property}") String myProperty) {  
			this.myProperty = myProperty;  
		}  
	  
		// ... 其他方法 ...  
	}

	这里的 @Value("${my.property}") String myProperty 表示,将配置文件中定义的my.property属性的值,注入到MyComponent类的构造函数中的myProperty参数中


注入到setter方法

	import org.springframework.beans.factory.annotation.Value;  
	import org.springframework.stereotype.Component;  
	  
	@Component  
	public class MyComponent {  
	  
		private String myProperty;  
	  
		@Value("${my.property}")  
		public void setMyProperty(String myProperty) {  
			this.myProperty = myProperty;  
		}  
	}

	这里的 @Value("${my.property}"),表示,将配置文件中定义的my.property属性的值,注入到setMyProperty方法的参数myProperty中,
	
	Spring在初始化"MyComponent bean"时,会自动调用这个方法,并将对应的属性值传入


注入到方法返回值


	import org.springframework.beans.factory.annotation.Value;  
	import org.springframework.context.annotation.Bean;  
	import org.springframework.context.annotation.Configuration;  
	  
	@Configuration  
	public class MyConfig {  
	  
		@Value("${my.property}")  
		@Bean
		public String myProperty() {  
			return "The value of my.property is: " + this.myProperty;  
		}  
	}

	在这个例子中,myProperty()方法,会返回一个字符串,其中包含 my.property 的值。


@Value(“#{xxxx}”)

@Value("#{xxxx}") 表示,使用Spring Expression Language (SpEL)来解析和计算xxxx这个表达式。


SpEL是一种强大的表达式语言,

	它支持查询和操作对象图、执行方法调用和访问JavaBean属性等,
	
	在`@Value`注解中使用`#{...}`语法,可以执行更复杂的操作,比如:调用bean的方法、引用其他的bean等。

举个例子

有一个bean定义了一个方法返回一个字符串,如下:


	@Component  
	public class MyComponent {  
		public String getMessage() {  
			return "Hello, World!";  
		}  
	}

可以在另一个bean中使用SpEL来调用这个方法并注入其结果:


	@Component  
	public class AnotherComponent {  
	  
		@Value("#{myComponent.getMessage()}")  
		private String message;  
	  
		// ... 其他方法 ...  
	}

	在这个例子中,"#{myComponent.getMessage()}" 是一个SpEL表达式,
	
	它调用了"MyComponent bean" 的 getMessage()方法,并将返回的结果,注入到AnotherComponent的message属性中。

标签:Spring,Value,value,MyComponent,property,my,myProperty
From: https://blog.csdn.net/pig_ning/article/details/137560173

相关文章

  • CEF编译报错:ValueError: path is on mount '\\\\tab_group_types.mojom-webui.js'
    F:\code\chromium_git\chromium\src>autoninja-Cout\Debug_GN_x64cef"f:\code\depot_tools\bootstrap-2@3_11_6_chromium_30_bin\python3\bin\python3.exe"F:\code\depot_tools\ninja.py-Cout\Debug_GN_x64cef-j10ninja:Enteringdirec......
  • a value of type "int" cannot be used to initialize an entity of type enum
    报错解释:这个报错信息表明你尝试使用一个整型(int)值去初始化一个枚举类型(enum)的实体,但是这样的操作是不允许的。在C++等编程语言中,枚举(enum)类型是一种用户定义的数据类型,它仅仅限定变量可以从一个预定义的常量值集合中取值。解决方法:要解决这个问题,你需要确保初始化枚举类型的实体......
  • Property [renew] not found. Using default value [false]
    接口请求时,报错Property[renew]notfound. Usingdefaultvalue[false]返回:Therewasanunexpectederror(type=NotFound,status=404).有两种可能:1、添加扫描路径使用basePackages:@ComponentScan(basePackages={"com.person","com.controller"})2、添加依赖......
  • MySQL数据库报错:ERROR 1364 (HY000): Field ‘authentication_string‘ doesn‘t have
    在MySQL安装和配置的过程中,遇到错误可能会让人感到困惑,尤其是当错误信息不够清晰时。本文将详细探讨一个在MySQL安装过程中较少见但可能会遇到的错误,提供一个全面的解决方案指南。错误描述在MySQL安装过程中,可能会遇到以下错误信息:ERROR1364(HY000):Field'authentica......
  • 学习Source Generators之IncrementalValueProvider
    前面我们使用了IIncrementalGenerator来生成代码,接下来我们来详细了解下IIncrementalGenerator的核心部分IncrementalValueProvider。介绍IncrementalValueProvider是基于管道的模式,将我们需要的数据进行处理转换后传递给SourceOutput。目前官方提供可用的Providers有如下几种:......
  • @Around(value =execution(* )) 的理解
    我们总是听到AOP,又称面向切面编程,那面向切面编程在日常开发中的应用场景有哪些呢?我们来一起梳理一下:什么时候会用到面向切面编程呢?其实就是有一些公共的逻辑,需要在很多地方用到,那这些代码如果在每个位置都写一下的话,当需要修改的时候,又必须将这些代码全都找出来进行修改,就会......
  • Django中values()和values_list()
    values()1、不带参数,返回所有属性的键值对,比如使用filter时,会返回一个列表,列表中每一项是一个字典>>>Blog.objects.values()[{'id':1,'name':'BeatlesBlog','tagline':'AllthelatestBeatlesnews.'}],>>>Blog.objects.filte......
  • java.sql.BatchUpdateException: Date truncation: Out of range value for column xx
    报错:java.sql.BatchUpdateException:Datetruncation:Outofrangevalueforcolumnxxxxx原因:xxx列ddl中为stock_num(12,2)数据库值为0.06需要更新为:0.06-0.21就会出现该错误参考:https://www.jb51.net/article/158166.htmhttps://blog.csdn.net/stone_tomca......
  • 【基于价值分解网络的多智能体协同学习】【VDN】 【Value-Decomposition Networks For
    目录Value-DecompositionNetworksForCooperativeMulti-AgentLearning基于价值分解网络(VDN)的多智能体协同学习Abstract 摘要1Introduction引言1.1OtherRelatedWork 1.1其他相关工作2Background 2背景2.1ReinforcementLearning2.1强化学习​2.2De......
  • wpf write value to config file and read the persisted value
    <Windowx:Class="WpfApp26.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.......