正如这里和这里所解释的,如何做到这一点很清楚,但似乎仍然无法使其工作。我只是喜欢使用 @Value 注释来将属性注入到 spring bean。我用一个控制器和一个 bean 创建了一个基本的 spring MVC 项目。
这是我的应用程序上下文:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<context:component-scan base-package="me.co.fatsecret" />
<!-- Properties -->
<bean id="props"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:fatProperties.properties" />
</bean>
</beans>
我有一个名为 Configuration 的 bean:
package me.co.fatsecret;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Configuration {
/*--- Members ---*/
@Value("${api_key}")
protected String API_KEY;
@Value("${api_secret}")
protected String API_SECRET;
@Value("${api_url}")
protected String API_URL;
/*--- Constructors ---*/
public Configuration() {
}
/*--- Getters & Setters ---*/
public String getAPI_KEY() {
return API_KEY;
}
public void setAPI_KEY(String aPI_KEY) {
API_KEY = aPI_KEY;
}
public String getAPI_SECRET() {
return API_SECRET;
}
public void setAPI_SECRET(String aPI_SECRET) {
API_SECRET = aPI_SECRET;
}
public String getAPI_URL() {
return API_URL;
}
public void setAPI_URL(String aPI_URL) {
API_URL = aPI_URL;
}
}
现在我只有一个控制器,注入了这个配置类,当我调用这个控制器时,我看到配置类中的值没有正确填充。
我的属性文件位于资源文件夹 (src/main/resources) 下,并且是我的类路径的一部分(默认情况下完成,因为这是一个 maven 项目)。这里是:
api_url=http://platform.fatsecret.com/js?
api_key=SomeKey
api_secret=SomeSecret
文件名为 fatProperties.properties。当我在调用控制器时调试服务器时,我看到 Configuration 类的内容是:
${api_key}
${api_secret}
${api_url}
这是字符串的实际值,这意味着属性文件中的值由于某种原因没有被注入。
我在这里错过了什么吗?
UPDATE1:我将 PropertyPlaceholderConfigurer bean 替换为:
<context:property-placeholder location="classpath:fatProperties.properties"/>
得到相同的结果