主要问题:
是否有人建议我如何使用Spring在我的Java代码中检索值,以从任何属性文件中获得由上下文指定的值:applicationContext.xml中的属性占位符标记?
详细描述:
我对春天很陌生。试图使用它来检索我的应用程序连接到(可配置的)JMS队列的可配置属性。
我有一个Java/J2EE web应用,使用Spring。
在src/main/resources/applicationContext.xml中我有以下行:
<context:property-placeholder location="classpath:myapp.properties" />
然后在src/main/resources/myapp。我有以下几行:
myservice.url=tcp://someservice:4002
myservice.queue=myqueue.service.txt.v1.q
我现在的问题是,无论如何,我都不知道如何获得我的服务的价值。在myapp中定义的Url。属性到运行的Java代码中
我已经尝试了一个静态函数[在应用程序中调用]:
public static String getProperty(String propName)
{
WebApplicationContext ctx =
FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
Environment env = ctx.getEnvironment();
retVal = env.getProperty(propName);
return retVal;
}
然而,当它返回一个已填充的环境对象"env"时,env.getProperty(propName)方法返回null。
好的,非常非常感谢Rustam给了我需要的线索。我是这样解决这个问题的:
在src/main/resources/applicationContext.xml中我有以下行:
<context:property-placeholder location="classpath:myapp.properties" />
然后在src/main/resources/myapp。我有以下几行:
myservice.url=tcp://someservice:4002
myservice.queue=myqueue.service.txt.v1.q
然后我有一个类如下:
package my.app.util;
import org.springframework.beans.factory.annotation.Value;
public class ConfigInformation
{
public ConfigInformation()
{
// Empty constructor needed to instantiate beans
}
@Value("${myservice.url}")
private String _myServiceUrl;
public String getMyServiceUrl()
{
return _myServiceUrl;
}
@Value("${myservice.queue}")
private String _myServiceQueue;
public String getMyServiceQueue()
{
return _myServiceQueue;
}
}
然后,我在我的applicationContext.xml中有以下声明:
<bean name="configInformation" class="my.app.util.ConfigInformation">
</bean>
完成这些之后,我可以在代码中使用以下行:
WebApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
ConfigInformation configInfo = (ConfigInformation) ctx.getBean("configInformation");
因此,configInfo对象被赋值给"myservice.url"one_answers";myservice.queue"可以通过方法调用来检索:
configInfo.getMyServiceUrl()
和
configInfo.getMyServiceQueue()