Detect if running in servlet container or offline

I have a simple problem: I want to configure an object differently based on whether the object is created in the servlet container or whether it is created in a stand-alone application.

The object is a database connection, and I take care of setting the request timeout.

The first solution I can come up with is:

if (insideServletContainer(this.getClass().getClassLoader()) { /// do some servlet specific config } else { /// do some standalone config } 

The question, of course, is that I can write a reliable method for determining whether a class has been loaded into a servlet container. At best, it looks like a hack.

The second option is to assume that the default case is an offline instance creation, sets default values ​​based on an offline configuration, and overrides them in the servlet context.

So, to summarize my question: Do you know about a good / reliable mechanism if the class was loaded from a servlet container? If not, I will have to go the second route.

Nick

+4
source share
4 answers

This seems like a very bad idea. Instead, why don't you let the class take parameters, and then let the container or application configure it accordingly?

+7
source

Distracting from this idea, I would suggest looking for java: comp / env, which will be available only on the EE server:

 try { new InitialContext().lookup("java:comp/env"); /// do some servlet specific config } catch (NamingException ex) { /// do some standalone config } 
+7
source

An alternative way to do this is to have a configuration introduced into this class by some boot loader.

In the standalone version, this will be done using the main() method (or something called from it).

In the webapp version, this will be done by the listener or the called filter in web.xml .

Injection injection is useful here because it eliminates the need for your application to check such things; instead, the application gets what it needs.

+4
source

I would recommend Injection Dependency as @matt b.

As a second option, if this is just a simple case that you have described, and you do not want to add or study the DI structure to support this function. You can do the same as your current code, using the properties file to load a different value based on the environment. You can simply use a different file for each environment and provide VM arg to indicate which environment you are working in.

 db_prop.dev db_prop.stalone dp_prop.int db_prop.prod 

Then you can load the resource

 "db_prop." + System.getProperty("runtime.env") 
0
source

Source: https://habr.com/ru/post/1311902/


All Articles