iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Spring@value用法示例详解
  • 515
分享到

Spring@value用法示例详解

2024-04-02 19:04:59 515人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

目录一、两种使用方法二、配置2.1 @Value(“#{configProperties[‘key’]}”)使用2.1.1配置文件:2

为了简化读取properties文件中的配置值,spring支持@value注解的方式来获取,这种方式大大简化了项目配置,提高业务中的灵活性。

一、两种使用方法

1、@Value(“#{configProperties[‘key’]}”)

2、@Value(“${key}”)

二、配置

2.1 @Value(“#{configProperties[‘key’]}”)使用

2.1.1配置文件:

配置方法1:
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="locations">
        <list>
            <value>classpath:value.properties</value>
        </list>
    </property>
</bean>

配置方法2:
<util:properties id="configProperties" location="classpath:value.properties"></util:properties>

注:配置1和配置2等价,这种方法需要util标签,要引入util的xsd:

Http://www.springframework.org/schema/util

http://www.springframework.org/schema/util/spring-util-3.0.xsd"

value.properties

key=1

ValueDemo.java

@Component
public class ValueDemo {
    @Value("#{configProperties['key']}")
    private String value;

    public String getValue() {
        return value;
    }
}

2.2 @Value(“${key}”)使用

2.2.1 配置文件

1、在2.1.1的配置文件基础上增加:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
    <property name="properties" ref="configProperties"/>
</bean>

2、直接指定配置文件,完整的配置:

<bean id="appProperty"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <array>
            <value>classpath:value.properties</value>
        </array>
    </property>
</bean>

ValueDemo.java

@Component
public class ValueDemo {
    @Value("${key}")
    private String value;

    public String getValue() {
        return value;
    }
}

到此这篇关于Spring-@value用法详解的文章就介绍到这了,更多相关Spring @value内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Spring@value用法示例详解

本文链接: https://www.lsjlt.com/news/165927.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作