配置web.xml
<!-- 用于加载变量 -->
<listener>
<listener-class>com.cs2c.bus.listener.LoadSysVariables</listener-class>
</listener>
该listener代码:
package com.cs2c.cobra.common.listener;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
*
* @author wangz
*
* 用于初始化系统变量,比如各种url等,JAR包中会从SYS中取,因此在此处设置
*
* 2012-05-30
*/
public class LoadSysVariables implements ServletContextListener{
private static final String SYS_CONFIG_FILE_NAME = "/config.properties";
private static final String COBRA_SERVER_URL_NAME= "cobra.server.url";
private static final String COBRA_ESBSERVER_URL_NAME= "sys_cobra_esbserver_url";
private static final String GLUSTER_ESBSERVER_URL_NAME = "gluster.server.url";
@Override
public void contextDestroyed(ServletContextEvent arg0) {
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
Properties props = new Properties();
try {
props.load(this.getClass().getResourceAsStream(SYS_CONFIG_FILE_NAME));
} catch (IOException e) {
e.printStackTrace();
}
System.setProperty(COBRA_ESBSERVER_URL_NAME,props.getProperty(COBRA_ESBSERVER_URL_NAME).toString());
System.setProperty(GLUSTER_ESBSERVER_URL_NAME,props.getProperty(GLUSTER_ESBSERVER_URL_NAME).toString());
System.setProperty("sys_cobra_conf_server_url",props.getProperty("sys_cobra_conf_server_url").toString());
}
}
config.properties文件放在class的根目录下既可。
客户端中是从system里读配置,如果读取到,则按照读取到的值,读取不到则使用默认值,例如:
import java.net.URI;
import javax.ws.rs.core.UriBuilder;
import com.cs2c.cobra.core.constants.CobraRESTConstants;
import com.cs2c.restful.jersey.client.AbstractHttpClient;
import com.cs2c.restful.jersey.utils.ClientConstants;
/**
* 监控数据的ESB的client
* @author wz
* 2012-05-24
*/
public abstract class AbstractCobraEsbClient extends AbstractHttpClient {
public URI getServerBaseURI() {
return UriBuilder.fromUri(getBaseURL()).build();
}
private String getBaseURL() {
// remove the platform path (e.g. /linux.gtk.x86_64) from the URL
return System.getProperty(CobraRESTConstants.RESOURCE_BASE_URL_NAME,
"http://10.1.83.29:8083");
}
}