Spring 引入properties配置文件的方式
来源:互联网 发布:windows socket 知乎 编辑:程序博客网 时间:2024/05/17 01:58
spring注入常量的方式,可以直接在java代码中使用
*.properties配置文件是在开发中常用的配置文件方式,一些需要经常变动的参数会以键值对的方式放在其中,然后可以在*.xml文件和java代码中直接引用,避免出现硬编码导致违反开闭原则。而咋Spring中直接引用properties配置文件有以下几种方式,在此记录,权作日记。
可以对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
- Spring 引入properties配置文件的方式
- spring 配置文件引入properties
- 在spring配置文件中引入properties文件--引出加载配置文件的对应方式
- spring 引入数据库配置(其他配置文件.properties)文件的两种方式
- spring 配置文件中 引入properties文件
- Spring 3 中引入properties配置文件
- Spring读取properties配置文件的三种方式
- spring基于xml加载和读取properties配置文件的方式
- spring-mybatis框架整合引入properties配置文件报错问题
- Spring-boot中读取核心配置文件application和自定义properties配置文件的方式
- Spring引入properties文件
- spring 引入properties文件
- Spring引入properties文件
- xml配置文件引入properties文件
- 通过Spring读取properties配置文件的信息 Spring 读取properties
- spring的配置文件中引入其他配置
- 两种解析properties配置文件的方式
- 读取配置文件properties的简单方式
- 冒泡排序
- iOS按钮倒计时
- ReactNativeiOS(一)编辑器
- 有两个不同版本的jQuery库,冲突的解决办法。
- C++primer plus第六版课后编程练习答案5.2
- Spring 引入properties配置文件的方式
- Java 开源网址
- android学习笔记14 - android.os包:系统功能调用和系统参数获取
- sftp文件上传和读取
- <10> go test单元测试
- 读取联系人
- Tomcat 7 访问 Manager 和 Host Manager
- ArtifactDescriptorException的解决方法
- android spinner 设置弹框和下拉方式