场景
假如有以下属性文件dev.properties, 需要注入下面的tag
tag=123
需要声明的是:在使用@Value 注解 注入参数时,在当前类需要给该属性提供Setter 方法!!
1.通过PropertyPlaceholderConfigurer<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="dev.properties" />
</bean>代码:
@Value("${tag}")
private String tag;2.通过PreferencesPlaceholderConfigurer
<bean id="appConfig" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="location" value="dev.properties" />
</bean>代码:
@Value("${tag}")
private String tag;与上面 PropertyPlaceholderConfigurer 用法 相同!
3.通过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;另外还有一种方式:
Spring中有个<context:property-placeholder location=""/>标签,可以用来加载properties配置文件,location是配置文件的路径,我们现在在工程目录的src下新建一个conn.properties文件,里面写上上面dataSource的配置:
<context:property-placeholder location="classpath:conn.properties"/><!-- 加载配置文件 --> <context:property-placeholder location=""/>标签也可以用下面的<bean>标签来代替,<bean>标签我们更加熟悉,可读性更强<!-- 与上面的配置等价,下面的更容易理解 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations"> <!-- PropertyPlaceholderConfigurer类中有个locations属性,接收的是一个数组,即我们可以在下面配好多个properties文件 -->
<array>
<value>classpath:conn.properties</value>
</array>
</property>
</bean> 虽然看起来没有上面的<context:property-placeholder location=""/>简洁,但是更加清晰,建议使用后面的这种。但是这个只限于xml的方式,即在beans.xml中用${key}获取配置文件中的值value。
本文介绍了Spring框架中使用@Value注解从属性文件加载配置的多种方法,包括通过PropertyPlaceholderConfigurer、PreferencesPlaceholderConfigurer和PropertiesFactoryBean。同时强调在使用@Value时,需为注入的属性提供对应的setter方法。示例代码展示了如何直接注入字面量值。
595

被折叠的 条评论
为什么被折叠?



