无法使用PropertyPlaceholderConfigurer在JNDI上下文中查找属性

时间:2012-04-25 13:22:31

标签: java spring properties jndi

我想从WEb.XML中删除env-entry

<env-entry>
    <description>String used in masking process</description>
    <env-entry-name>default_mask</env-entry-name>
    <env-entry-value>*</env-entry-value>
    <env-entry-type>java.lang.String</env-entry-type>
</env-entry>

所以我创建了一个具有(c:/my.properties)

的属性文件
default_mask=9999   

所以我尝试使用像JndiPropertyPlaceholderConfigurer这样的现有解决方案(来自Spring Jndi Context and PropertyPlaceholderConfigurer ) 并在spring的applicationcontext.xml中配置为

<bean  
class="com.test.webappl.JndiPropertyPlaceholderConfigurer">  
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/> 
<property name="ignoreResourceNotFound" value="true"/> 
<property name="location" value="file:c:\my.properties"/>  

启动Tomcat服务器会读取属性文件,如

.......com.test.webappl.JndiPropertyPlaceholderConfigurer] Loading properties file from URL [file:c:/my.properties]

现在我读java时读了

Context context = new InitialContext(); 
String resource = context.lookup("java:comp/env/default_mask");  

应用程序抛出以下错误

**javax.naming.NameNotFoundException: Name default_mask is not bound in this Context**

我在web.xml中的弹簧设置也是

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationcontext.xml</param-value>
</context-param>

有人知道我是否使用了正确的方法? 我知道这已在Spring Jndi Context and PropertyPlaceholderConfigurer中得到解答,但不知何故不适用于我的情况

先谢谢

2 个答案:

答案 0 :(得分:0)

如果要将任何内容部署到任何应用程序服务器,最好将所有相关资源打包到部署单元(在您的情况下为war)。

要回答你的问题 - 如果你使用spring向JNDI容器注入任何东西,你也应该让spring找到适合你的一切。

所以你不能使用

new InitialContext(); // this has nothing to do with spring.

希望这会有所帮助:)

答案 1 :(得分:0)

您正在尝试(或期望)做的是“将名称值对从您的my.properties绑定到JNDI上下文”。

<强> BUT

您提到的示例并不是这样做的。只是做了以下事情

  1. 如果在上下文文件中引用了属性占位符(如${my.name}),那么它将从JNDI解析它(假设它已存在)
  2. 如果JNDI无法使用它,则将其解析为属性文件的默认读取。
  3. 没有关于将变量绑定到JNDI的详细信息。没有提及bind()方法。
  4. 现在,      要解决您的问题,即获取一些方法来读取属性文件并将其绑定到JNDI树,一种方法是跟随

    1. 您可以创建一个班级JndiPropertyBinder并在其中注入jndiTemplate
    2. 在此课程中注入您的媒体资源
    3. 现在在bean上写一个init hook,其中将读取文件中的所有属性并将它们绑定到jndi树。
    4. 使这个bean按顺序加载,以便在使用它的所有其他bean之前加载它。
相关问题