我目前正在基於Spring 3.1.0.M1的基於註釋的Web應用程序上工作,並且我在解決應用程序的一個特定位置中的屬性佔位符時遇到問題。如何以編程方式解決Spring中的屬性佔位符
這是故事。
1)在我的web應用程序的上下文(由DispatcherServlet的加載),我有
MVC-config.xml中:
<!-- Handles HTTP GET requests for /resources/version/** -->
<resources mapping="/${app.resources.path}/**" location="/static/" cache-period="31556926"/>
...
<!-- Web properties -->
<context:property-placeholder location="
classpath:app.properties
"/>
2)內部app.properties,有2個屬性,除其他:
app.properties:
# Properties provided (filtered) by Maven itself
app.version: 0.1-SNAPSHOT
...
# Static resources mapping
app.resources.path: resources/${app.version}
3)我有我的JS JSP定製標記P 2.1模板。這個標籤負責根據環境設置,應用版本,彈簧主題選擇等完成資源路徑構建。自定義標籤類擴展了spring:url實現類,所以它可以被認爲是一個普通的url標籤,但是有一些關於正確路徑的額外知識。
我的問題是我無法在我的JSP自定義標記實現中正確解析$ {app.resources.path}。 JSP自定義標籤由servlet容器管理,而不是Spring,因此不參與DI。所以我不能僅僅使用通常的@Value(「$ {app.resources.path}」)並且讓Spring自動解決它。
我在那裏有所有的Web應用程序上下文實例,所以我必須通過編程解決我的財產。
到目前爲止,我嘗試:
ResourceTag.java:
// returns null
PropertyResolver resolver = getRequestContext().getWebApplicationContext().getBean(PropertyResolver.class);
resolver.getProperty("app.resources.path");
// returns null, its the same web context instance (as expected)
PropertyResolver resolver2 = WebApplicationContextUtils.getRequiredWebApplicationContext(pageContext.getServletContext()).getBean(PropertyResolver.class);
resolver2.getProperty("app.resources.path");
// throws NPE, resolver3 is null as StringValueResolver is not bound
StringValueResolver resolver3 = getRequestContext().getWebApplicationContext().getBean(StringValueResolver.class);
resolver3.resolveStringValue("app.resources.path");
// null, since context: property-placeholder does not register itself as PropertySource
Environment env = getRequestContext().getWebApplicationContext().getEnvironment();
env.getProperty("app.resources.path");
所以現在我有點堅持這一點。我知道解決佔位符問題的能力在上下文中的某個位置,我只是不知道正確的方法。
任何幫助或想法檢查是高度讚賞。
謝謝Ritesh。我想我可以使用這個解決方案,以防萬一找不到更優雅的東西。 – 2011-03-03 02:39:58
已將此答案標記爲已接受,但找到純程序化解決方案總是很有趣。 – 2011-03-09 18:13:59
@Max Alexejev您還可以擴展PropertyPlaceholderConfigurer並將在第二個參數中傳遞的已解析屬性捕獲到processProperties方法。但是,您將不得不使用bean配置而不是上下文:property-placeholder。 – Ritesh 2011-03-09 18:50:43