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

2025-05-29 0 84

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

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

新建配置文件jdbc.properties

?

1

2
username=root

password=root

新建并配置文件spring-properties

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17
<?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>

新建单元测试

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14
@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的单元测试框架也没有怎么研究,如果知道的读者可以再下方留言告述我,如果没人回答的话只能以后有时间慢慢研究了。

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

原文链接:http://www.jianshu.com/p/c5fb54266415

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 详解利用Spring加载Properties配置文件 https://www.kuaiidc.com/117642.html

相关文章

发表评论
暂无评论