当前位置: 移动技术网 > IT编程>开发语言>Java > 详解利用Spring加载Properties配置文件

详解利用Spring加载Properties配置文件

2019年07月22日  | 移动技术网IT编程  | 我要评论

记得之前写web项目的时候配置文件的读取都是用properties这个类完成的,当时为了项目的代码的统一也就没做什么改动。但事后一直在琢磨springmvc会不会都配置的注解功能了?经过最近的研究返现springmvc确实带有这一项功能,spring确实很强大。

因为代码很简单,我就贴上我测试的代码,按照步骤做就可以实现了。

新建配置文件jdbc.properties

username=root
password=root

新建并配置文件spring-properties

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
   xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="configproperties" class="org.springframework.beans.factory.config.propertiesfactorybean">
   <property name="locations">
     <list>
       <value>classpath:jdbc.properties</value>
     </list>
   </property>
   <property name="fileencoding" value="utf-8"/>
 </bean>
 <bean id="propertyconfigurer" class="org.springframework.beans.factory.config.preferencesplaceholderconfigurer">
   <property name="properties" ref="configproperties"/>
 </bean>
</beans>

新建单元测试

@runwith(springjunit4classrunner.class)
@contextconfiguration(locations = "classpath:spring/spring-properties.xml")
public class testtrans {
 @value("#{configproperties['username']}")
 private string username;
 @value("#{configproperties['password']}")
 private string password;
 @test
 public void testproperties(){
   system.out.println("---");
   system.out.println(username);
   system.out.println(password);
 }
}

使用上面这种方式注解properties的话intelij idea会有提示的,按住ctrl然后将鼠标点击属性'username'会调入到对应的配置文件中,这样也可以验证我们的配置是否生效。

现在虽然知道如何使用注解加载配置文件了,但是propertiesfactorybean和preferencesplaceholderconfigurer的区别和作用还没有弄清楚,另外spring的单元测试框架也没有怎么研究,如果知道的读者可以再下方留言告述我,如果没人回答的话只能以后有时间慢慢研究了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网