gpt4 book ai didi

Spring Jndi Context 和 PropertyPlaceholderConfigurer

转载 作者:行者123 更新时间:2023-12-04 14:17:22 37 4
gpt4 key购买 nike

使用 Spring,我想读取 Webspehere 上下文中的变量。

Read a Environment Variable in Java with Websphere

在 web.xml 中定义数据....

<env-entry>
<env-entry-name>varName</env-entry-name>
<env-entry-value>56</env-entry-value>
<env-entry-type>java.lang.String</env-entry-type>
</env-entry>

用java看
Context envEntryContext = (Context) new InitialContext().lookup("java:comp/env");
String mydata = (String)envEntryContext.lookup(“varName”);

但我想在我的 common.xml 中获取数据
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/context/servweb.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders">
<value>true</value>
</property>
</bean>

也许有类似的东西
 <constructor-arg>
<jee:jndi-lookup jndi-name="java:comp/env" default-value="data" />
</constructor-arg>

但在上下文中做同样的事情
Context envEntryContext = (Context) new InitialContext().lookup("java:comp/env");
String mydata = (String)envEntryContext.lookup(“varName”);

也许是这样的:
 <constructor-arg>
<jee:jndi-lookup jndi-name="java:comp/env">
<jee:environment>
varName=default
</jee:environment>
</jee:jndi-lookup>

有人知道正确的方法吗?

提前致谢

最佳答案

您可以创建自己的 PropertyPlaceholderConfigurer

public class JndiPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

private String jndiPrefix = "java:comp/env/";
private JndiTemplate jndiTemplate = new JndiTemplate();

@Override
protected String resolvePlaceholder(String placeholder, Properties props) {
String value = null;
value = resolveJndiPlaceholder(placeholder);
if (value == null) {
value = super.resolvePlaceholder(placeholder, props);
}
return value;
}

private String resolveJndiPlaceholder(String placeholder) {
try {
String value = (String)jndiTemplate.lookup(jndiPrefix + placeholder, String.class);
return value;
} catch (NamingException e) {
// ignore
}
return null;
}

public void setJndiPrefix(String jndiPrefix) {
this.jndiPrefix = jndiPrefix;
}

public void setJndiTemplate(JndiTemplate jndiTemplate) {
this.jndiTemplate = jndiTemplate;
}
}

然后在您的 applicationContext.xml 中使用它
<bean id="propertyPlaceholderConfigurer"
class="mypkg.helper.JndiPropertyPlaceholderConfigurer">
<property name="properties">
<props>
<prop key="varName">default</prop>
</props>
</property>
</bean>

或用于在属性文件中定义默认值
<bean id="propertyPlaceholderConfigurer"
class="mypkg.helper.JndiPropertyPlaceholderConfigurer">
<property name="location" value="classpath:/defaults.properties"/>
</bean>

关于Spring Jndi Context 和 PropertyPlaceholderConfigurer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8998704/

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