使用PropertyPlaceholderConfigurer指定配置文件和@Value 注解获取properties值

为了简化读取properties文件中的配置值,spring支持@value注解的方式来获取,这种方式大大简化了项目配置,提高业务中的灵活性。

一、两种使用方法

1、@Value("#{configProperties['key']}")

2、@Value("${key}")

二、配置

2.1 @Value("#{configProperties['key']}")使用

2.1.1配置文件:

[html]  view plain  copy
  1. 配置方法1:  
  2. <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
  3.     <property name="locations">  
  4.         <list>  
  5.             <value>classpath:value.properties</value>  
  6.         </list>  
  7.     </property>  
  8. </bean>  
[html]  view plain  copy
  1. 配置方法2:  
  2. <util:properties id="configProperties" location="classpath:value.properties"></util:properties>  
注:配置1和配置2等价,这种方法需要util标签,要引入util的xsd:

http://www.springframework.org/schema/util

http://www.springframework.org/schema/util/spring-util-3.0.xsd"

value.properties

[html]  view plain  copy
  1. key=1  

ValueDemo.java

[java]  view plain  copy
  1. @Component  
  2. public class ValueDemo {  
  3.     @Value("#{configProperties['key']}")  
  4.     private String value;  
  5.   
  6.     public String getValue() {  
  7.         return value;  
  8.     }  
  9. }  

2.2 @Value("${key}")使用

2.2.1 配置文件

1、在2.1.1的配置文件基础上增加:

[html]  view plain  copy
  1. <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">  
  2.     <property name="properties" ref="configProperties"/>  
  3. </bean>  

或者使用PropertyPlaceholderConfigurer直接指定配置文件,完整的配置:
[html]  view plain  copy
  1. <bean id="appProperty"  
  2.           class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  3.     <property name="locations">  
  4.         <array>  
  5.             <value>classpath:value.properties</value>  
  6.         </array>  
  7.     </property>  
  8. </bean>  

ValueDemo.java
[java]  view plain  copy
  1. @Component  
  2. public class ValueDemo {  
  3.     @Value("${key}")  
  4.     private String value;  
  5.   
  6.     public String getValue() {  
  7.         return value;  
  8.     }  
  9. }  


[java]  view plain  copy
  1. @Controller  
  2. @RequestMapping("/value")  
  3. public class ValuePropertyController extends ApplicationController{  
  4.       
  5.     @Value("#{configProperties['jdbc.jdbcUrl']}")  
  6.     private String jdbcUrl;   
  7.       
  8.     @RequestMapping  
  9.     public String value(){  
  10.         System.out.println(jdbcUrl);  
  11.         return "";  
  12.     }  
  13. }  


applicationContext.xml

[html]  view plain  copy
  1. <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
  2.        <property name="locations">  
  3.            <list>  
  4.                <value>classpath:database.properties</value>  
  5.            </list>  
  6.        </property>  
  7.     </bean>  
  8.     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">  
  9.         <property name="properties" ref="configProperties" />  
  10.     </bean>  

database.properties

[html]  view plain  copy
  1. jdbc.jdbcUrl=jdbc:mysql://localhost:3306/commentDemo?useUnicode=true&characterEncoding=UTF-8  

@Value("${key}")使用还有一种配置方法:

Spring : How To Load Properties File using @Value Annotation

This example shows how to load the properties file values using the @Value annotation. Accessing the property file values in the Spring application involves the following steps:

Add the property file details to spring bean configuration file. You have to use the “classpath” prefix if you want to load the files from the classpath.
Create a properties file in the same name that is configured in the XML file and put it under the classpath folders. In most scenarios, source folders will be by default kept under the classpath.
Use @Value annotation to get the property valye. @Value annotation takes the string parameter which is “key” used in the properties file. This annotation has to be used with variables to inject the value.
Lets look at the following example code:


1. Spring MVC Configurations


spring4-mvc-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:websocket="http://www.springframework.org/schema/websocket"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/websocket
        http://www.springframework.org/schema/websocket/spring-websocket-4.0.xsd">


<context:component-scan base-package="com.javabeat.controller" />
<context:property-placeholder location="classpath:application.properties"/>
<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/jsp/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>

</beans>




2. Application Properties File

application.properties

msg=Spring Application Properties!!
3. Spring MVC Controller


HelloController.java


package com.javabeat.controller;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
@RequestMapping("/welcome")
public class HelloController {
@Value("${msg}")
private String msg;


@RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("msg", this.msg);
return "hello";


}


}
4. Views


hello.jsp

<html>
<body>
Your Message : ${msg}
</body>
</html>
5. Web Deployment Descriptor


web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Spring MVC 4.0 Web Application</display-name>
<servlet>
<servlet-name>spring4-mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>


<servlet-mapping>
<servlet-name>spring4-mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
6. Demo


If you run the above example, you would get the below output.