gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:13:12 25 4
gpt4 key购买 nike

我有一个使用 Spring 和 JSF 的 Java Web 应用程序,部署在 Tomcat 中。作为记录,在 web.xml ,只配置了 Faces servlet;没有 Spring servlet。

我的 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从定义可以看出我正在注入(inject)一个外部属性,在本例中,它是一个环境变量。此属性通过 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 中注入(inject)这个环境变量,如下所示:

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

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

使用上面的配置,一切正常 - 所有接线都没有任何缺陷。

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

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

最佳答案

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

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

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

关于java - 当属性占位符在 Spring 上下文(JNDI 方面)中定义时,幕后会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21702005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com