[英]Spring reading properties from application.properties file with wildcard
[英]Reading from properties file in spring
我有一個使用Spring MVC的Web應用程序。 我在sample.properties
文件中定義了幾個常量。 spring-servlet是為我的應用程序中的所有URL初始化的servlet。 彈簧的servlet:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<context:property-placeholder location="classpath:sample.properties"/>
</beans>
在我的一個Java類中,我訪問以下屬性之一的值:
package com.sample;
import com.google.gson.JsonArray;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Validator {
@Value("${credit}")
String credits;
private static final Logger LOG = Logger.getLogger(Validator.class);
public void checkRating() {
LOG.debug(credits);
}
}
sample.properties:
credit=[{"duration":15,"credit":10},{"duration":30,"credit":20}]
從控制器調用Validator時,它只是將其記錄為${credit}
到我的日志文件中。 我沒有得到它的價值。 同樣,如果我在屬性文件中放置一個整數/浮點數,則會收到一條錯誤消息,指出無法將其轉換為整數/浮點數。 我是否缺少任何配置?
這樣做的原因是因為propertyplaceholder configurer是BeanFactoryPostProcessor ,它僅處理在配置propertyplaceholder的上下文中定義的bean。 在Web應用程序通常有作為解釋上下文的層次結構在這里 。 因此,您需要在適當的位置進行聲明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.