spring value注解注入 详解Spring通过@Value注解注入属性的几种方式

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

spring value注解注入 详解Spring通过@Value注解注入属性的几种方式

Ydoing   2021-03-24 我要评论
想了解详解Spring通过@Value注解注入属性的几种方式的相关内容吗,Ydoing在本文为您仔细讲解spring value注解注入的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:spring,value注解注入,spring,注解注入,Spring,Value,注解,下面大家一起来学习吧。

场景

假如有以下属性文件dev.properties, 需要注入下面的tag

tag=123

通过PropertyPlaceholderConfigurer

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location" value="dev.properties" />
</bean>

代码

@Value("${tag}")
private String tag;

通过PreferencesPlaceholderConfigurer

<bean id="appConfig" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
  <property name="location" value="dev.properties" />
</bean>

代码:

@Value("${tag}")
private String tag;

通过PropertiesFactoryBean

  <bean id="config" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="location" value="dev.properties" />
  </bean>

代码:

@Value("#{config['tag']}")
private String tag;

通过util:properties

效果同PropertiesFactoryBean一样

代码:

@Value("#{config['tag']}")
private String tag;

其他方式

有时也可以不通过文件,直接写字面量

<bean id="appConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <!--<property name="location" value="classpath:${env}.properties" />-->
  <property name="properties">
    <props>
      <prop key="tag">123</prop>
    </props>
  </property>
</bean>

代码:

@Value("${tag}")
private String tag;

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们