详解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;
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
导入项目出现Java多个工程相互引用异常A cycle was detected in the build path o
今天小编就为大家分享一篇关于导入项目出现Java多个工程相互引用异常A cycle was detected in the build path of project的解决办法,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧2018-12-12
浅谈String类型等值比较引起的“==”、“equals()”和“hashCode”思考
这篇文章主要介绍了浅谈String类型等值比较引起的“==”、“equals()”和“hashCode”思考。具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-09-09
SpringBoot配置Spring Security的实现示例
本文主要介绍了SpringBoot配置Spring Security的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2024-10-10
如何使用 Spring Boot 和 Canal 实现 My
本文介绍了如何使用SpringBoot和Canal实现MySQL数据库之间的数据同步,通过配置主库、创建Canal用户、配置CanalServer以及开发SpringBoot客户端,实现了将主库的数据实时同步到多个从库,感兴趣的朋友跟随小编一起看看吧2025-02-02


最新评论