spring - 如何在 Spring 中以编程方式解析属性占位符

标签 spring jsp dependency-injection jsp-tags custom-tag

我目前正在开发一个基于 Spring 3.1.0.M1、基于注释的 Web 应用程序,但在我的应用程序的一个特定位置解析属性占位符时遇到了问题。

这是故事。

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) 我的 JSP 2.1 模板中有一个 JSP 自定义标记。这个标签负责根据环境设置、应用程序版本、spring 主题选择等来构建完整的资源路径。自定义标签类扩展了 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");

所以现在我有点坚持。我知道解决占位符的能力是在上下文中的某个地方,我只是不知道正确的方法。
任何帮助或检查的想法都非常感谢。

最佳答案

自 Spring 3.0.3 以来,EmbeddedValueResolverAware 的工作方式与另一篇使用 appContext.getBeanFactory().resolveEmbeddedValue("${prop}") 调用的帖子中提到的相同。

解决问题:

  1. 让你的类实现 EmbeddedValueResolverAware 接口(interface),你会为你注入(inject)解析器

  2. 然后,您将可以在哪里检索属性,如代码片段所示:

    String propertyValue = resolver.resolveStringValue("${your.property.name}");
    

那么你的 bean 就不需要依赖 ApplicationContext 来检索你需要的属性了。

关于spring - 如何在 Spring 中以编程方式解析属性占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5172392/

相关文章:

java - 在 Eclipse 中使用相同主机但不同端口运行两个 Web 应用程序

spring - 使用Spring Boot进行Kotlin集成测试

java - 如何构建一个同时暴露rest和soap服务的Spring Boot jar

java - Tomcat:如何将不同的目录指向同一个 WEB-INF

java - Injector.getInstance(..) 为单例返回一个新实例

c# - Ninject 方法级拦截带参数

java - Spring Framework中applicationContext.xml和spring-servlet.xml的区别

java - 如何从 servlet 使用保存文件对话框?

jsp - 了解 JSP errorPage 属性

python - django View 中的依赖注入(inject)