Spring中的@Value注解详解

这篇具有很好参考价值的文章主要介绍了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文件配置,获得里面配置的端口号

Spring中的@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 {

    /**
     *Get in application.yml
     */
    @Value("${server.port}")
    private String port;
    
    @Test
    public  void  getPort(){
       System.out.println(port);
    }
}

程序结果

Spring中的@Value注解详解

自定义yml文件,application-config.yml文件配置,获得里面配置的用户密码值

注意,如果想导入自定义的yml配置文件,应该首先把自定义文件在application.yml文件中进行注册,自定义的yml文件要以application开头,形式为application-fileName

Spring中的@Value注解详解

配置信息

Spring中的@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 {
    /**
     *Get in application-config.yml
     */
    @Value("${user.password}")
    private String password;
    
    @Test
    public  void  getPassword(){
       System.out.println(password);
    }
}

程序结果

Spring中的@Value注解详解

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

配置信息

Spring中的@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;

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;
    
    @Test
    public  void  getTools(){
       System.out.println(toolArray);
       System.out.println(toolList);
    }
}

程序结果

Spring中的@Value注解详解

基于非配置文件的注入

在使用示例说明基于非配置文件注入属性的实例之前,让我们看一下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;
    
    
    @Test
    public  void  getValue(){
    
        System.out.println(str);
    }	
}

程序结果

Spring中的@Value注解详解

注入操作系统属性

可以利用 @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
    
    @Test
    public  void  getValue(){
    
        System.out.println(osName);
    }
}

程序结果

Spring中的@Value注解详解

注入表达式结果

在 @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;
    
    @Test
    public  void  getValue(){
    
        System.out.println(randomNumber);
    }
}

程序结果

Spring中的@Value注解详解

注入其他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;
    
    @Test
    public  void  getValue(){
    
        System.out.println(fromAnotherBean);
    }
}

程序结果

Spring中的@Value注解详解

注入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;
    
    @Test
    public  void  getValue(){
    
        System.out.println(homePage);
    }
} 

程序结果

Spring中的@Value注解详解文章来源地址https://www.toymoban.com/news/detail-458141.html

到了这里,关于Spring中的@Value注解详解的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Spring 中的 @ConditionalOnProperty 注解

    介绍@ConditionalOnProperty注解的主要目的。 通常,在开发基于Spring的应用程序时,可能需要根据配置属性的存在和值有条件地创建一些bean。 例如,取决于是否将属性值设置为“ prod”或“ test”,可能想要注册一个DataSource bean来指向生产或测试数据库。 幸运的是,实现这一目标

    2024年02月16日
    浏览(26)
  • Spring中的注解

    Spring的配置 spring 2.5前==xml spring 2.5后==xml+annotation spring 3.0后==annotation+JavaConfig配置类 注解: 1.注入类 替换:bean id=\\\"\\\" class=\\\"\\\"/bean 位置:类 语法:@Component(value=\\\"注入容器中的id,如果省略id为类名且首字母小写,value属性名称可以省略\\\") eg: bean id=\\\"user\\\" class=\\\"com.apesource.包.User\\\"/bean  

    2024年01月20日
    浏览(22)
  • Spring中的自定义注解

    在Spring中,注解是一种非常使用的工具。 因其强大的功能,极大的提高了我们开发效率。 但是当遇到一些特殊业务时,框架自有的注解已经不能满足我们的需求了,这时我们就可以添加自定义注解来满足我们的业务需求。 我们用 @interface 来声明这是一个注解类。 另外需要在

    2024年02月11日
    浏览(39)
  • Spring Boot 中的 @Cacheable 注解

    在 Spring Boot 中,缓存是一个非常重要的话题。当我们需要频繁读取一些数据时,为了提高性能,可以将这些数据缓存起来,避免每次都从数据库中读取。为了实现缓存,Spring Boot 提供了一些缓存注解,其中最常用的是 @Cacheable 注解。 @Cacheable 注解用于标记一个方法需要被缓存

    2024年02月12日
    浏览(49)
  • Spring Boot 中的 @CacheEvict 注解

    在 Spring Boot 中,缓存是提高应用性能的重要手段。为了更好地管理缓存,Spring Boot 提供了一系列的缓存注解,其中 @CacheEvict 注解用于清空缓存。 本文将介绍 @CacheEvict 注解的含义、原理以及如何使用。 @CacheEvict 注解用于清空缓存。它可以标注在方法上,表示在执行该方法后

    2024年02月09日
    浏览(33)
  • Spring Boot 中的 @HystrixCommand 注解

    在分布式系统中,服务之间的调用是不可避免的。但随着服务数量的增加,服务之间的依赖关系也会变得越来越复杂,服务的故障也会变得越来越常见。一旦某个服务出现故障,它所依赖的服务也会受到影响,导致整个系统出现故障。为了应对这种情况,Netflix 开发了 Hystri

    2024年02月17日
    浏览(23)
  • Spring Boot 中的 @EnableDiscoveryClient 注解

    Spring Boot 是一个快速开发 Spring 应用程序的框架,它提供了一些基础设施,使得我们可以快速地开发出高效、可靠的应用程序。其中,@EnableDiscoveryClient 注解是 Spring Boot 中一个非常重要的注解,它提供了一种便捷的方式来将 Spring Boot 应用程序注册到服务注册中心中。本文将介

    2024年02月12日
    浏览(34)
  • Spring Boot中的@EnableAutoConfiguration注解

    Spring Boot是一个非常流行的Java框架,它可以快速创建基于Spring的应用程序。Spring Boot提供了许多自动配置功能,使得开发者可以非常容易地创建一个可运行的应用程序。其中,@EnableAutoConfiguration注解是Spring Boot自动配置功能的核心之一。 @EnableAutoConfiguration注解是Spring Boot的核心

    2024年02月11日
    浏览(51)
  • Spring框架中的@Conditional系列注解

    Conditional 是由SpringFramework提供的一个注解,位于 org.springframework.context.annotation 包内,定义如下。 SpringBoot 模块大量的使用@Conditional 注释,我们可以将Spring的@Conditional注解用于以下场景: 可以作为类级别的注解直接或者间接的与@Component相关联,包括@Configuration类; 可以作为元

    2024年02月08日
    浏览(29)
  • Spring MVC中的一些常用注解

    目录 @RequestMapping 实现路由映射 限制请求方式 @PathVariable 从url中获取变量的值 更改绑定参数的名字 @RequestParam 可以传递集合  更改绑定参数的名字 可修改是否为必传参数 @RequestBody 获取请求正文的内容  可修改是否为必传参数 @RequestPart 可以支持上传文件 更改绑定参数的名字

    2024年01月19日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包