码迷,mamicode.com
首页 > 编程语言 > 详细

spring-自动加载配置文件\使用属性文件注入

时间:2016-06-26 18:27:52      阅读:326      评论:0      收藏:0      [点我收藏+]

标签:

上一篇jsf环境搭建的基础上 , 加入spring框架 , 先看下目录结构

技术分享

src/main/resources 这个source folder 放置web项目所需的主要配置,打包时,会自动打包到WEB-INF下

首先看下pom.xml,需要引入一些依赖项:

技术分享 pom.xml

 

1. 自动加载配置文件

在web项目中,可以让spring自动加载配置文件(即上图中的src/main/resouces/spring下的xml文件),WEB-INF/web.xml中参考以下设置:

技术分享 web.xml

解释一下: classpath*:spring/applicationContext-*.xml 这里表示将加载classpath路径下 spring目录下的所有以applicationContext-开头的xml文件 , 通常为了保持配置文件的清爽 , 我们会把配置分成多份 : 比如 applicationContext-db.xml 用来配置DataSource , applicationContext-cache.xml用来配置缓存...等等.

 

2.代码中如何取得ApplicationContext实例

技术分享 ApplicationContextUtils

 有了这个工具类 , 就可以方便的取得注入的Bean

 

3. 使用properties文件注入

为了演示注入效果,先定义一个基本的Entity类

技术分享 ProductEntity

然后在applicationContext-beans.xml中配置以下内容:

技术分享 spring配置文件

注:classpath:properties/*.properties表示运行时 , spring容器会自动加载classpath\properties目录下的所有以.properties后缀结尾的文件 ,  我们在src/main/resources/properties/下放置一个product.properties属性文件 , 内容如下:

技术分享 product.properties

该文件被spring自动加载后 , 就可以用里面定义的属性值 , 为Bean做setter属性注入 , 即配置文件中的<property name="productId" value="${product.id}" />

 

4.验证注入是否成功

在HomeController里 ,  向Spring容器要一个Bean ,  显示下它的属性:

技术分享 HomeController

index.xhtml里仍然跟上篇相同:

技术分享 index.xhtml

 

最后部署到jboss上 , 运行截图如下:

技术分享

 

 

spring-自动加载配置文件\使用属性文件注入

标签:

原文地址:http://www.cnblogs.com/w-wfy/p/5618201.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!