---
title: "spring父子容器与读取properties文件"
author: "m635674608"
date: "2017-11-09T09:51:11Z"
tags: []
categories: ["编程语言"]
slug: "spring-properties"
draft: false
lastmod: "2017-11-08T11:35:05Z"
id: 2399019
url: "https://m635674608.iteye.com/blog/2399019"
---

读取properties文件中的内容，可以使用@Value

比如

@Value("${url}")  
public String url;

properties文件内容是 url=xxxxxx

但是它只能在它所在容器中使用。比如spring容器中加载了properties文件，但你这个注解使用在springmvc容器（子容器）的Controller中，那么是获取不到的。

\-------------------------------------------------

关于父子容器：

子容器能够访问父容器的资源，父容器能够访问子容器的资源。

我们在web.xml中其实配置的就是父子容器org.springframework.web.context.ContextLoaderListener和org.springframework.web.servlet.DispatcherServlet。因为我们在DispatcherServlet中的param-value是spring-servlet.xml，所以，即使你在applicationContext.xml中加载了controller也是没用的，只有spring-servlet.xml中加载controller才有用。

\-------------------------------------------------

因为@Value("${url}")这种用法。所以有两种方式使用，

第一种，如果你要在子容器中使用@Value，那么就得把properties文件在spring-servlet.xml中引入。

第二种，因为子容器能访问父容器资源，那就在子容器中创建一个@Service或@Repository等注解的类，专门封装properties文件中的信息。那么子容器可以通过@Autowired对象去得到properties文件中信息。

推荐使用第二种方式。

 

http://blog.csdn.net/u011302734/article/details/75503467