Spring 引入properties配置文件的方式

来源:互联网 发布:windows socket 知乎 编辑:程序博客网 时间:2024/05/17 01:58

spring注入常量的方式,可以直接在java代码中使用

*.properties配置文件是在开发中常用的配置文件方式,一些需要经常变动的参数会以键值对的方式放在其中,然后可以在*.xml文件和java代码中直接引用,避免出现硬编码导致违反开闭原则。而咋Spring中直接引用properties配置文件有以下几种方式,在此记录,权作日记。


方法一:采用配置文件<util:**>标签方式来配置
可以对set、map、list、properties文件等类型的数据进行配置,以下以properties文件为例说明使用方法步骤:
1、applicationContext.xml中添加
<beans xmlns:util="http://www.springframework.org/schema/util"  xsi:schemaLocation="http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">  </beans>


2、使用标签引入properties文件路径

<util:properties id="configEnv" location="config/env.properties" />

3、在代码中注入

@Value("#configEnv['db_key']")private String db_key;


Tips:
1、一定要使用spring2.0以上版本方才支持此功能
2、db_key 可以是Boolean、int、Double等其他基本类型
方法二:使用PropertyPlaceholderConfigurer方式完成配置文件载入
<bean id="appProperty"    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations"><array><value>classpath:app.properties</value></array></property></bean>


然后使用@Value("${db_key}")直接注入使用
Tips:
1、此种方式还可以用标签<context:property-placeholder>来代替 使用方式:
<context:property-placeholder            ignore-resource-not-found="true"            location="classpath*:/application.properties,                      classpath*:/db.properties" />


location 可以一次引入多个文件
2、变量的前缀就此丢失了,因此需要在变量的key中加入前缀,以保证不会重名,一般格式:db.conn.maxConns = 30
3、此种方式注入通用性更好,可以在Spring配置文件中直接使用。如:
<bean id="dataSource" class=""><property id="username" value="${db.oracle.username}"></property><property id="password" value="${db.oracle.password}"></property></bean>


4、还可以不通过spring配置文件而直接在程序中加载properties文件的方法,如:
context = new ClassPathXmlApplicationContext("applicationContext.xml");PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();cfg.setLocation(new FileSystemResource("classpath*:/config/util.properties"));cfg.setBeanFactory(context);



0 0