当在Spring上下文(JNDI方面)中定义属性占位符时,在幕后会发生什么



我有一个使用Spring和JSF的Java web应用程序,部署在Tomcat中。对于记录,在web.xml中,只配置FacesServlet;没有Springservlet。

我的Spring上下文的入口点是applicationContext.xml,它看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" 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.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<context:component-scan base-package="my.pack" annotation-config="true" />
<context:property-placeholder location="file:${admin.config.path}/database.properties"/>
<context:spring-configured />
<context:annotation-config />
<aop:aspectj-autoproxy />
</beans>

property-placeholder定义中,可以看到我正在注入一个外部属性,在本例中,它是一个环境变量。此属性通过Tomcat上下文配置传递,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/cntxt">
<Environment name="admin.config.path" value="d:/conf/"
type="java.lang.String" override="false"/>
</Context>

我还在Spring管理的一个bean中注入了这个环境变量,如下所示:

@Value("${java:comp/env/admin.config.path}")
private String confDir;

(这是因为我还将该目录用于其他一些配置文件,这些文件不是.properties文件)。

有了上面的配置,一切都很好——所有的布线都没有任何缺陷。

但是,在某个时刻,我不再需要通过database.properties中的属性占位符配置器注入属性(但我仍然需要admin.config.path中的其他文件),因此我从applicationContext.xml中删除了<context:property-placeholder>行。这时,使用@Value的注入在我的Spring托管bean中停止了工作。

有人知道到底发生了什么吗?如果没有在Spring上下文中定义属性占位符配置器,那么JNDI注入似乎失败了。有没有什么方法可以重新启用这种注入(而无需定义指向空属性文件的伪属性占位符)?

您需要一个属性占位符配置器实例,它的唯一目的是用实际值替换占位符。如果删除它,则不会替换占位符。

添加一个<context:property-placeholder />并省略location字段,或者添加一个类型为PropertySourcesPlaceholderConfigurer的bean。无论哪种方式,都将重新启用占位符支持。

小建议删除属性的java:comp/env部分,默认情况下,如果无法在其他位置解析属性(servlet上下文、属性、系统属性等),它将执行JNDI查找。

最新更新