---
title: "Spring 注解学习手札（一） 构建简单Web应用"
author: "wxyfighting"
date: "2013-06-12T09:13:00Z"
tags: []
slug: "spring-web"
draft: false
lastmod: "2013-06-12T14:31:13Z"
id: 1885587
url: "https://wxyfighting.iteye.com/blog/1885587"
---

我们将用到如下jar包：

引用

aopalliance-1.0.jar  
commons-logging-1.1.1.jar  
log4j-1.2.15.jar  
spring-beans-2.5.6.jar  
spring-context-2.5.6.jar  
spring-context-support-2.5.6.jar  
spring-core-2.5.6.jar  
spring-tx-2.5.6.jar  
spring-web-2.5.6.jar  
spring-webmvc-2.5.6.jar

先看web.xml

Xml代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. &lt;?xmlversion="1.0"encoding="UTF-8"?&gt;
02. &lt;web-app
03. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04. xmlns="http://java.sun.com/xml/ns/javaee"
05. xmlns:web="http://java.sun.com/xml/ns/javaee/web-app\_2\_5.xsd"
06. xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app\_2\_5.xsd"
07. id="WebApp\_ID"
08. version="2.5"&gt;
09. &lt;display-name&gt;spring&lt;/display-name&gt;
10. &lt;!--应用路径--&gt;
11. &lt;context-param&gt;
12. &lt;param-name&gt;webAppRootKey&lt;/param-name&gt;
13. &lt;param-value&gt;spring.webapp.root&lt;/param-value&gt;
14. &lt;/context-param&gt;
15. &lt;!--Log4J配置--&gt;
16. &lt;context-param&gt;
17. &lt;param-name&gt;log4jConfigLocation&lt;/param-name&gt;
18. &lt;param-value&gt;classpath:log4j.xml&lt;/param-value&gt;
19. &lt;/context-param&gt;
20. &lt;context-param&gt;
21. &lt;param-name&gt;log4jRefreshInterval&lt;/param-name&gt;
22. &lt;param-value&gt;60000&lt;/param-value&gt;
23. &lt;/context-param&gt;
24. &lt;!--Spring上下文配置--&gt;
25. &lt;context-param&gt;
26. &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
27. &lt;param-value&gt;/WEB-INF/applicationContext.xml&lt;/param-value&gt;
28. &lt;/context-param&gt;
29. &lt;!--字符集过滤器--&gt;
30. &lt;filter&gt;
31. &lt;filter-name&gt;CharacterEncodingFilter&lt;/filter-name&gt;
32. &lt;filter-class&gt;org.springframework.web.filter.CharacterEncodingFilter&lt;/filter-class&gt;
33. &lt;init-param&gt;
34. &lt;param-name&gt;encoding&lt;/param-name&gt;
35. &lt;param-value&gt;UTF-8&lt;/param-value&gt;
36. &lt;/init-param&gt;
37. &lt;init-param&gt;
38. &lt;param-name&gt;forceEncoding&lt;/param-name&gt;
39. &lt;param-value&gt;true&lt;/param-value&gt;
40. &lt;/init-param&gt;
41. &lt;/filter&gt;
42. &lt;filter-mapping&gt;
43. &lt;filter-name&gt;CharacterEncodingFilter&lt;/filter-name&gt;
44. &lt;url-pattern&gt;/\*&lt;/url-pattern&gt;
45. &lt;/filter-mapping&gt;
46. &lt;!--Spring监听器--&gt;
47. &lt;listener&gt;
48. &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
49. &lt;/listener&gt;
50. &lt;listener&gt;
51. &lt;listener-class&gt;org.springframework.web.util.Log4jConfigListener&lt;/listener-class&gt;
52. &lt;/listener&gt;
53. &lt;!--Spring分发器--&gt;
54. &lt;servlet&gt;
55. &lt;servlet-name&gt;spring&lt;/servlet-name&gt;
56. &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
57. &lt;init-param&gt;
58. &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
59. &lt;param-value&gt;/WEB-INF/servlet.xml&lt;/param-value&gt;
60. &lt;/init-param&gt;
61. &lt;/servlet&gt;
62. &lt;servlet-mapping&gt;
63. &lt;servlet-name&gt;spring&lt;/servlet-name&gt;
64. &lt;url-pattern&gt;\*.do&lt;/url-pattern&gt;
65. &lt;/servlet-mapping&gt;
66. &lt;welcome-file-list&gt;
67. &lt;welcome-file&gt;index.html&lt;/welcome-file&gt;
68. &lt;welcome-file&gt;index.htm&lt;/welcome-file&gt;
69. &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
70. &lt;welcome-file&gt;default.html&lt;/welcome-file&gt;
71. &lt;welcome-file&gt;default.htm&lt;/welcome-file&gt;
72. &lt;welcome-file&gt;default.jsp&lt;/welcome-file&gt;
73. &lt;/welcome-file-list&gt;
74. &lt;/web-app&gt;

有不少人问我，这段代码是什么：

Xml代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

1. &lt;!--应用路径--&gt;
2. &lt;context-param&gt;
3. &lt;param-name&gt;webAppRootKey&lt;/param-name&gt;
4. &lt;param-value&gt;spring.webapp.root&lt;/param-value&gt;
5. &lt;/context-param&gt;

这是当前应用的路径变量，也就是说你可以在其他代码中使用${spring.webapp.root}指代当前应用路径。我经常用它来设置log的输出目录。  
为什么要设置参数log4jConfigLocation？

Xml代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

1. &lt;!--Log4J配置--&gt;
2. &lt;context-param&gt;
3. &lt;param-name&gt;log4jConfigLocation&lt;/param-name&gt;
4. &lt;param-value&gt;classpath:log4j.xml&lt;/param-value&gt;
5. &lt;/context-param&gt;
6. &lt;context-param&gt;
7. &lt;param-name&gt;log4jRefreshInterval&lt;/param-name&gt;
8. &lt;param-value&gt;60000&lt;/param-value&gt;
9. &lt;/context-param&gt;

这是一种基本配置，spring中很多代码使用了不同的日志接口，既有log4j也有commons-logging，这里只是强制转换为log4j！并且，log4j的配置文件只能放在classpath根路径。同时，需要通过commons-logging配置将日志控制权转交给log4j。同时commons-logging.properties必须放置在classpath根路径。  
commons-logging内容：

Properties代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

1. org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger

最后，记得配置log4j的监听器：

Xml代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

1. &lt;listener&gt;
2. &lt;listener-class&gt;org.springframework.web.util.Log4jConfigListener&lt;/listener-class&gt;
3. &lt;/listener&gt;

接下来，我们需要配置两套配置文件，applicationContext.xml和servlet.xml。  
applicationContext.xml用于对应用层面做整体控制。按照分层思想，统领service层和dao层。servlet.xml则单纯控制controller层。

Xml代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. &lt;?xmlversion="1.0"encoding="UTF-8"?&gt;
02. &lt;beans
03. xmlns="http://www.springframework.org/schema/beans"
04. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
05. xmlns:context="http://www.springframework.org/schema/context"
06. xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd
07. http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"&gt;
08. &lt;import
09. resource="service.xml"/&gt;
10. &lt;import
11. resource="dao.xml"/&gt;
12. &lt;/beans&gt;

applicationContext.xml什么都不干，它只管涉及到整体需要的配置，并且集中管理。  
这里引入了两个配置文件service.xml和dao.xml分别用于业务、数据处理。  
service.xml

Xml代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. &lt;?xmlversion="1.0"encoding="UTF-8"?&gt;
02. &lt;beans
03. xmlns="http://www.springframework.org/schema/beans"
04. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
05. xmlns:context="http://www.springframework.org/schema/context"
06. xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd
07. http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"&gt;
08. &lt;context:component-scan
09. base-package="org.zlex.spring.service"/&gt;
10. &lt;/beans&gt;

注意，这里通过&lt;context:component-scan /&gt;标签指定了业务层的基础包路径——“org.zlex.spring.service”。也就是说，业务层相关实现均在这一层。这是有必要的分层之一。  
dao.xml

Xml代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. &lt;?xmlversion="1.0"encoding="UTF-8"?&gt;
02. &lt;beans
03. xmlns="http://www.springframework.org/schema/beans"
04. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
05. xmlns:aop="http://www.springframework.org/schema/aop"
06. xmlns:context="http://www.springframework.org/schema/context"
07. xmlns:tx="http://www.springframework.org/schema/tx"
08. xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd
09. http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd
10. http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd
11. http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd"&gt;
12. &lt;context:component-scan
13. base-package="org.zlex.spring.dao"/&gt;
14. &lt;/beans&gt;

dao层如法炮制，包路径是"org.zlex.spring.dao"。从这个角度看，注解还是很方便的！![](http://snowolf.iteye.com/images/smiles/icon_biggrin.gif)  
最后，我们看看servlet.xml

Xml代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. &lt;?xmlversion="1.0"encoding="UTF-8"?&gt;
02. &lt;beans
03. xmlns="http://www.springframework.org/schema/beans"
04. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
05. xmlns:context="http://www.springframework.org/schema/context"
06. xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd
07. http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"&gt;
08. &lt;context:component-scan
09. base-package="org.zlex.spring.controller"/&gt;
10. &lt;bean
11. id="urlMapping"
12. class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/&gt;
13. &lt;bean
14. class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/&gt;
15. &lt;/beans&gt;

包路径配置就不细说了，都是一个概念。最重要的时候后面两个配置，这将使得注解生效！![](http://snowolf.iteye.com/images/smiles/icon_biggrin.gif)  
“org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping”是默认实现，可以不写，Spring容器默认会默认使用该类。  
“org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter”直接关系到多动作控制器配置是否可用！  
简单看一下代码结构，如图：  
![](http://dl.iteye.com/upload/attachment/197483/acfea974-d089-30fd-8820-0f502566e777.jpg)  
Account类是来存储账户信息，属于域对象，极为简单，代码如下所示：  
Account.java

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. /\**
02. \*2010-1-23
03. \*/
04. packageorg.zlex.spring.domain;
05. importjava.io.Serializable;
06. /\**
07. \*
08. \*@author&lt;ahref="mailto:zlex.dongliang@gmail.com"&gt;梁栋&lt;/a&gt;
09. \*@version1.0
10. \*@since1.0
11. \*/
12. publicclassAccountimplementsSerializable{
13. /\**
14. \*
15. \*/
16. privatestaticfinallongserialVersionUID=-533698031946372178L;
17. privateStringusername;
18. privateStringpassword;
19. /\**
20. \*@paramusername
21. \*@parampassword
22. \*/
23. publicAccount(Stringusername,Stringpassword){
24. this.username=username;
25. this.password=password;
26. }
27. /\**
28. \*@returntheusername
29. \*/
30. publicStringgetUsername(){
31. returnusername;
32. }
33. /\**
34. \*@paramusernametheusernametoset
35. \*/
36. publicvoidsetUsername(Stringusername){
37. this.username=username;
38. }
39. /\**
40. \*@returnthepassword
41. \*/
42. publicStringgetPassword(){
43. returnpassword;
44. }
45. /\**
46. \*@parampasswordthepasswordtoset
47. \*/
48. publicvoidsetPassword(Stringpassword){
49. this.password=password;
50. }
51. }

通常，在构建域对象时，需要考虑该对象可能需要进行网络传输，本地缓存，因此建议实现序列化接口Serializable![](http://snowolf.iteye.com/images/smiles/icon_biggrin.gif)  
我们再来看看控制器，这就稍微复杂了一点代码如下所示：  
AccountController .java

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. /\**
02. \*2010-1-23
03. \*/
04. packageorg.zlex.spring.controller;
05. importjavax.servlet.http.HttpServletRequest;
06. importjavax.servlet.http.HttpServletResponse;
07. importorg.springframework.beans.factory.annotation.Autowired;
08. importorg.springframework.stereotype.Controller;
09. importorg.springframework.web.bind.ServletRequestUtils;
10. importorg.springframework.web.bind.annotation.RequestMapping;
11. importorg.springframework.web.bind.annotation.RequestMethod;
12. importorg.zlex.spring.service.AccountService;
13. /\**
14. \*
15. \*@author&lt;ahref="mailto:zlex.dongliang@gmail.com"&gt;梁栋&lt;/a&gt;
16. \*@version1.0
17. \*@since1.0
18. \*/
19. @Controller
20. @RequestMapping("/account.do")
21. publicclassAccountController{
22. @Autowired
23. privateAccountServiceaccountService;
24. @RequestMapping(method=RequestMethod.GET)
25. publicvoidhello(HttpServletRequestrequest,HttpServletResponseresponse)
26. throwsException{
27. Stringusername=ServletRequestUtils.getRequiredStringParameter(
28. request,"username");
29. Stringpassword=ServletRequestUtils.getRequiredStringParameter(
30. request,"password");
31. System.out.println(accountService.verify(username,password));
32. }
33. }

分段详述：

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

1. @Controller
2. @RequestMapping("/account.do")

这两行注解，@Controller是告诉Spring容器，这是一个控制器类，@RequestMapping("/account.do")是来定义该控制器对应的请求路径（/account.do）

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

1. @Autowired
2. privateAccountServiceaccountService;

这是用来自动织入业务层实现AccountService，有了这个注解，我们就可以不用写setAccountService()方法了！![](http://snowolf.iteye.com/images/smiles/icon_biggrin.gif)  
同时，JSR-250标准注解，推荐使用@Resource来代替Spring专有的@Autowired注解。

引用

Spring 不但支持自己定义的@Autowired注解，还支持几个由JSR-250规范定义的注解，它们分别是@Resource、@PostConstruct以及@PreDestroy。

　　@Resource的作用相当于@Autowired，只不过@Autowired按byType自动注入，而@Resource默认按 byName自动注入罢了。@Resource有两个属性是比较重要的，分别是name和type，Spring将@Resource注解的name属性解析为bean的名字，而type属性则解析为bean的类型。所以如果使用name属性，则使用byName的自动注入策略，而使用type属性时则使用byType自动注入策略。如果既不指定name也不指定type属性，这时将通过反射机制使用byName自动注入策略。

　　@Resource装配顺序

　　1. 如果同时指定了name和type，则从Spring上下文中找到唯一匹配的bean进行装配，找不到则抛出异常

　　2. 如果指定了name，则从上下文中查找名称（id）匹配的bean进行装配，找不到则抛出异常

　　3. 如果指定了type，则从上下文中找到类型匹配的唯一bean进行装配，找不到或者找到多个，都会抛出异常

　　4. 如果既没有指定name，又没有指定type，则自动按照byName方式进行装配（见2）；如果没有匹配，则回退为一个原始类型（UserDao）进行匹配，如果匹配则自动装配；

　　1.6. @PostConstruct（JSR-250）

在方法上加上注解@PostConstruct，这个方法就会在Bean初始化之后被Spring容器执行（注：Bean初始化包括，实例化Bean，并装配Bean的属性（依赖注入））。

这有点像ORM最终被JPA一统天下的意思！![](http://snowolf.iteye.com/images/smiles/icon_biggrin.gif)大家知道就可以了，具体使用何种标准由项目说了算！![](http://snowolf.iteye.com/images/smiles/icon_smile.gif)  
最后，来看看核心方法：

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

1. @RequestMapping(method=RequestMethod.GET)
2. publicvoidhello(HttpServletRequestrequest,HttpServletResponseresponse)
3. throwsException{
4. Stringusername=ServletRequestUtils.getRequiredStringParameter(
5. request,"username");
6. Stringpassword=ServletRequestUtils.getRequiredStringParameter(
7. request,"password");
8. System.out.println(accountService.verify(username,password));
9. }

注解@RequestMapping(method = RequestMethod.GET)指定了访问方法类型。  
注意，如果没有用这个注解标识方法，Spring容器将不知道那个方法可以用于处理get请求！![](http://snowolf.iteye.com/images/smiles/icon_smile.gif)  
对于方法名，我们可以随意定！方法中的参数，类似于“HttpServletRequest request, HttpServletResponse response”，只要你需要方法可以是有参也可以是无参！  
解析来看Service层，分为接口和实现：  
AccountService.java

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. /\**
02. \*2010-1-23
03. \*/
04. packageorg.zlex.spring.service;
05. /\**
06. \*
07. \*@author&lt;ahref="mailto:zlex.dongliang@gmail.com"&gt;梁栋&lt;/a&gt;
08. \*@version1.0
09. \*@since1.0
10. \*/
11. publicinterfaceAccountService{
12. /\**
13. \*验证用户身份
14. \*
15. \*@paramusername
16. \*@parampassword
17. \*@return
18. \*/
19. booleanverify(Stringusername,Stringpassword);
20. }

接口不需要任何Spring注解相关的东西，它就是一个简单的接口！  
重要的部分在于实现层，如下所示：  
AccountServiceImpl.java

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. /\**
02. \*2010-1-23
03. \*/
04. packageorg.zlex.spring.service.impl;
05. importorg.springframework.beans.factory.annotation.Autowired;
06. importorg.springframework.stereotype.Service;
07. importorg.springframework.transaction.annotation.Transactional;
08. importorg.zlex.spring.dao.AccountDao;
09. importorg.zlex.spring.domain.Account;
10. importorg.zlex.spring.service.AccountService;
11. /\**
12. \*
13. \*@author&lt;ahref="mailto:zlex.dongliang@gmail.com"&gt;梁栋&lt;/a&gt;
14. \*@version1.0
15. \*@since1.0
16. \*/
17. @Service
18. @Transactional
19. publicclassAccountServiceImplimplementsAccountService{
20. @Autowired
21. privateAccountDaoaccountDao;
22. /*
23. \*(non-Javadoc)
24. \*
25. \*@seeorg.zlex.spring.service.AccountService#verify(java.lang.String,
26. \*java.lang.String)
27. \*/
28. @Override
29. publicbooleanverify(Stringusername,Stringpassword){
30. Accountaccount=accountDao.read(username);
31. if(password.equals(account.getPassword())){
32. returntrue;
33. }else{
34. returnfalse;
35. }
36. }
37. }

注意以下内容：

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

1. @Service
2. @Transactional

注解@Service用于标识这是一个Service层实现，@Transactional用于控制事务，将事务定位在业务层，这是非常务实的做法！![](http://snowolf.iteye.com/images/smiles/icon_smile.gif)  
接下来，我们来看持久层：AccountDao和AccountDaoImpl类  
AccountDao.java

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. /\**
02. \*2010-1-23
03. \*/
04. packageorg.zlex.spring.dao;
05. importorg.zlex.spring.domain.Account;
06. /\**
07. \*
08. \*@author&lt;ahref="mailto:zlex.dongliang@gmail.com"&gt;梁栋&lt;/a&gt;
09. \*@version1.0
10. \*@since1.0
11. \*/
12. publicinterfaceAccountDao{
13. /\**
14. \*读取用户信息
15. \*
16. \*@paramusername
17. \*@return
18. \*/
19. Accountread(Stringusername);
20. }

这个接口就是简单的数据提取，无需任何Spring注解有关的东西！  
再看其实现类：  
AccountDaoImpl.java

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. /\**
02. \*2010-1-23
03. \*/
04. packageorg.zlex.spring.dao.impl;
05. importorg.springframework.stereotype.Repository;
06. importorg.zlex.spring.dao.AccountDao;
07. importorg.zlex.spring.domain.Account;
08. /\**
09. \*
10. \*@author&lt;ahref="mailto:zlex.dongliang@gmail.com"&gt;梁栋&lt;/a&gt;
11. \*@version1.0
12. \*@since1.0
13. \*/
14. @Repository
15. publicclassAccountDaoImplimplementsAccountDao{
16. /\*(non-Javadoc)
17. \*@seeorg.zlex.spring.dao.AccountDao#read(java.lang.String)
18. \*/
19. @Override
20. publicAccountread(Stringusername){
21. returnnewAccount(username,"wolf");
22. }
23. }

这里只需要注意注解：

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

1. @Repository

意为持久层，Dao实现这层我没有过于细致的介绍通过注解调用ORM或是JDBC来完成实现，这些内容后续细述！  
这里我们没有提到注解@Component，共有4种“组件”式注解：

引用

@Component:可装载组件  
@Repository:持久层组件  
@Service:服务层组件  
@Controller:控制层组件

这样spring容器就完成了控制层、业务层和持久层的构建。  
启动应用，访问[http://localhost:8080/spring/account.do?username=snow&password=wolf](http://localhost:8080/spring/account.do?username=snow&password=wolf)  
观察控制台，如果得到包含“true”的输出，本次构建就成功了！![](http://snowolf.iteye.com/images/smiles/icon_biggrin.gif)  
![](http://dl.iteye.com/upload/attachment/197488/9447d026-3250-30cd-962d-88da029687f8.jpg)  
代码见附件！![](http://snowolf.iteye.com/images/smiles/icon_biggrin.gif)

顺便说一句：在Spring之前的XML配置中，如果你想在一个类中获得文件可以通过在xml配置这个类的某个属性。在注解的方式（Spring3.0）中，你可以使用@Value来指定这个文件。  
例如，我们想要在一个类中获得一个文件，可以这样写：

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

1. @Value("/WEB-INF/database.properties")
2. privateFiledatabaseConfig;

如果这个properties文件已经正常在容器中加载，可以直接这样写：

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

1. @Value("${jdbc.url}")
2. privateStringurl;

获得这个url参数！![](http://snowolf.iteye.com/images/smiles/icon_biggrin.gif)

容器中加载这个Properties文件：

Xml代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

1. &lt;util:propertiesid="jdbc"location="/WEB-INF/database.properties"/&gt;

这样，我们就能通过注解@Value获得/WEB-INF/database.properties这个文件！![](http://snowolf.iteye.com/images/smiles/icon_biggrin.gif)  
如果我们想要获得注入在xml中的某个类，例如dataSource（&lt;bean id ="dataSource"&gt;）可以在注解的类中这么写：

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

1. @Resource(name="dataSource")
2. privateBasicDataSourcedataSource;

如果只有这么一个类使用该配置文件：

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

1. @ImportResource("/WEB-INF/database.properties")
2. publicclassAccountDaoImplextendsAccountDao{

就这么简单！![](http://snowolf.iteye.com/images/smiles/icon_biggrin.gif)