在项目中有些参数经常需要修改,或者后期可能会有改动时,那我们最好把这些参数放到properties文件中,在源代码中读取properties里面的配置,这样后期只需要改动properties文件即可,不需要修改源码。下面讨论spring两种加载方式,基于xml和基于注解的加载方式。

1. 通过xml方式加载properties文件

以Spring实例化dataSource为例,先在工程目录的src下新建一个conn.properties文件,里面写上上面dataSource的配置:

dataSource=com.mchange.v2.c3p0.ComboPooledDataSource
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/shop
username=root
password=root

然后在只需要在beans.xml中做如下修改即可:

 <context:property-placeholder location="classpath:conn.properties"/><!-- 加载配置文件 -->  

 <!-- com.mchange.v2.c3p0.ComboPooledDataSource类在c3p0-0.9.5.1.jar包的com.mchange.v2.c3p0包中 -->
<bean id="dataSource" class="${dataSource}"> <!-- 这些配置Spring在启动时会去conn.properties中找 -->
<property name="driverClass" value="${driverClass}" />
<property name="jdbcUrl" value="${jdbcUrl}" />
<property name="user" value="${user}" />
<property name="password" value="${password}" />
</bean>

标签也可以用下面的标签来代替,可读性更强:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations"> <!-- PropertyPlaceholderConfigurer类中有个locations属性,接收的是一个数组,即我们可以在下面配好多个properties文件 -->
<array>
<value>classpath:conf.properties</value>
</array>
</property>
</bean>

2. 通过注解方式加载properties文件

首先新建一个资源文件:public.properties

shop.url=http://magic/shop

第一种配置方式:

    <!-- 确保可在@Value中, 使用SeEL表达式获取资源属性 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties" ref="configProperties" />
</bean> <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:config/*.properties</value>
</list>
</property>
</bean>

在java代码中用@Value获取配置属性值

    @Value("${shop.url}")
private String url;

还有一种方式更简洁:

    <bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="fileEncoding" value="UTF-8"/>
<property name="locations"><!-- 这里是PropertiesFactoryBean类,它也有个locations属性,也是接收一个数组,跟上面一样 -->
<array>
<value>classpath:public.properties</value>
</array>
</property>
</bean>
<!--或者-->
<context:property-placeholder location="classpath:public.properties" /> //注意,这种表达式要有set方法才能被注入进来,注解写在set方法上即可
private String url;
@Value("#{prop.shop.url}")
//@Value表示去beans.xml文件中找id="prop"的bean,它是通过注解的方式读取properties配置文件的,然后去相应的配置文件中读取key=shop.url的对应的value值
public void setUrl(String url) {
this.token= url;
}

3.通过 @PropertySource和@Value 来读取配置文件

@Component
@PropertySource(value = {"classpath:common.properties", "classpath:abc.properties"})
public class Configs { @Value("${connect.api.apiKeyId}")
public String apiKeyId; @Value("${connect.api.secretApiKey}")
public String secretApiKey; public String getApiKeyId() {
return apiKeyId;
} public String getSecretApiKey() {
return secretApiKey;
}
}

我们来具体分析下:

1、@Component注解说明这是一个普通的bean,在Component Scanning时会被扫描到并被注入到Bean容器中;我们可以在其它引用此类的地方进行自动装配。@Autowired这个注解表示对这个bean进行自动装配。 比如:

@Controller
public class HomeController { @Autowired
private Configs configs;
}

2、@PropertySource注解用来指定要读取的配置文件的路径从而读取这些配置文件,可以同时指定多个配置文件;

3、@Value("${connect.api.apiKeyId}")用来读取属性key=connect.api.apiKeyId所对应的值并把值赋值给属性apiKeyId;

在项目中有些参数经常需要修改,或者后期可能会有改动时,那我们最好把这些参数放到properties文件中,在源代码中读取properties里面的配置,这样后期只需要改动properties文件即可,不需要修改源码。下面讨论spring两种加载方式,基于xml和基于注解的加载方式。

Spring详解(十)加载配置文件的更多相关文章

  1. 详解ListView加载网络图片的优化,让你轻松掌握!

    详解ListView加载网络图片的优化,让你轻松掌握! 写博客辛苦了,转载的朋友请标明出处哦,finddreams(http://blog.csdn.net/finddreams/article/de ...

  2. 微服务架构 | *2.3 Spring Cloud 启动及加载配置文件源码分析(以 Nacos 为例)

    目录 前言 1. Spring Cloud 什么时候加载配置文件 2. 准备 Environment 配置环境 2.1 配置 Environment 环境 SpringApplication.prep ...

  3. 【Spring学习笔记-2】Myeclipse下第一个Spring程序-通过ClassPathXmlApplicationContext加载配置文件

    *.hl_mark_KMSmartTagPinkImg{background-color:#ffaaff;}*.hl_mark_KMSmartTagBlueImg{background-color:# ...

  4. linux modprobe命令参数及用法详解--linux加载模块命令

    转:http://www.linuxso.com/command/modprobe.html modprobe(module probe) 功能说明:自动处理可载入模块. 语 法:modprobe [ ...

  5. Spring的 classpath 通配符加载配置文件

    http://www.cnblogs.com/taven/archive/2012/10/24/2737556.html classpath:app-Beans.xml 说明:无通配符,必须完全匹配 ...

  6. 详解Class加载过程

    1.Class文件内容格式 2.一个class文件是被加载到内存的过程是怎样的? loading 把一个class文件装到内存里,class文件是一个二进制,一个个的字节 linking Verifi ...

  7. 详解ListView加载网络图片的优化

    我们来了解一些ListView在加载大量网络图片的时候存在的常见问题: 1.性能问题,ListView的滑动有卡顿,不流畅,造成非常糟糕的用户体验. 2.图片的错位问题. 3.图片太大,加载Bitma ...

  8. Google推荐——Glide使用详解(图片加载框架)

    零.前言 本文所使用的Glide版本为3.7.0 一.简介 Glide,一个被google所推荐的图片加载库,作者是bumptech.这个库被广泛运用在google的开源项目中,包括2014年的goo ...

  9. spring boot 使用 EnvironmentAware 加载配置文件

    @Configuration public class PropertiesUtils implements EnvironmentAware { private int redisExpireTim ...

随机推荐

  1. C语言:printf标志符

    %d 十进制整数 %i %lf双精度浮点数 %o八进制整数  0%o或0%O %x十六进制整数  0x%x 或  0X%X %f单精度浮点数 %E  %e科学计数法 %s  字符串 %c  字符(单个 ...

  2. asp.net 读取 connectionStrings

    connectionStrings 在vs.net 2005 beta 2开始,如果你在web.config中使用了数据库连接字符串的配置,那么应该按如下的方法去写: <connectionSt ...

  3. 使用BeautifulSoup自动爬取微信公众号图片

    爬取微信分享的图片,根据不同的页面自行修改,使用BeautifulSoup爬取,自行格局HTML修改要爬取图片的位置 import re import time import requests imp ...

  4. File类与常用IO流第十一章——打印流

    第十一章.打印流 概述:java.io.PrintStream extends OutputStream,为其他输出流添加了功能,使题目能够方便的打印各种数据值表示形式. 特点: 只负责数据的输出,不 ...

  5. Cypress 高级用法系列 一

    1. Multiple Assertions cy .get('[data-cy=task]') .then( item => { expect(item[0]).to.contain.text ...

  6. 用好Git stash,助你事半功倍

    git stash: 用法:git stash list [<选项>] 或:git stash show [<选项>] [<stash>] 或:git stash ...

  7. 【LeetCode】297. 二叉树的序列化与反序列化

    297. 二叉树的序列化与反序列化 知识点:二叉树:递归 题目描述 序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一 ...

  8. etcd raft 处理流程图系列1-raftexample

    最近在看raft相关的代码和实现,发现etcd的raft模块在实现上还是比较灵活的,但缺点就是需要用户实现比较多的功能,如存储和网络等,同时带来的优点就是不会对用户的存储和传输作限制.网上对该模块的描 ...

  9. 如何在 NetCore 中定义我们自己的JSON配置文件的管理器。

    一.介绍 微软已经对外提供了新的平台,我们叫它们是 Net Core 平台,这个平台和 Net Framework 平台有本质的区别,这个最本质的区别就是微软的C#代码可以跨平台了.当前我们主流的3大 ...

  10. QML用Instantiator动态创建顶级窗口

    关键点 使用Model驱动Instantiator QML里面的hashmap: QQmlPropertyMap 上一次说到用 QQmlApplicationEngine 多次load的方式创建多个一 ...