我在tomat主进程中运行了两个Web应用程序,这意味着我认为应该有两个独立的程序,每个应用程序一个。
另一件事是两个应用都使用了JVM属性,我想要特定于应用程序。
//common-service library used in both web-apps
public class CommonService {
private static Logger logger = LogManager.getLogger(CommonService.class);
static {
String uuid = UUID.randomUUID().toString();
logger.debug("CommonService initialization for {}" , uuid);
System.setProperty("key1", "value1-"+ uuid);
}
}
当我为每个应用部署战争并查看key1
属性的值时,它会被第二个加载的应用程序覆盖。
正如我在这里展示的那样,
加载app1时,属性key1
的值
但是在加载app2后,它会覆盖app1的key1
。
上面的代码非常简单,
public class Service1Servlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
CommonService commonService = new CommonService();
System.out.println("Service1 key1= " + System.getProperty("key1"));
PrintWriter out = resp.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h1>" + System.getProperty("key1")+ "</h1>");
out.println("</body>");
out.println("</html>");
}
}
所以,似乎我只能在单个JVM中拥有JVM参数全局,但我在我的服务器上运行多个服务,其中每个服务都需要有自己的一组JVM参数,根据这些参数,还有另一个实际使用的api那个JVM属性。
答案 0 :(得分:2)
对于应用程序属性,您不想使用VM参数。正如您所发现的,这些对整个容器来说都是全局的。相反,您应该使用在加载应用程序时加载的属性文件。我喜欢使用的一种方法是将资源包加载到静态Map中。我们假设你有一个&#34; application.properties&#34; WEB-INF / classes目录中的文件。像这样:
//common-service library used in both web-apps
public class CommonService {
public static Map< String, String > APPLICATION_PROPERTIES = new HashMap<>();
static {
ResourceBundle bundle = ResourceBundle.getBundle( "application" );
for( String key : bundle.keySet() ) {
APPLICATION_PROPERTIES.put( key, ( String )bundle.getObject( key ) );
}
}
}
然后,当您想要访问应用程序属性时,可以在代码中执行此操作:
String key1Value = CommonService.APPLICATION_PROPERTIES.get( "key1" );