I have created ServletContextListener in below class. Also I have created static block in another class of the same package. which would run first in servlet type application. that static block is not running at all.
@WebListener
public class BaclkgroundJobManager implements ServletContextListener {
private ScheduledExecutorService scheduler;
public void contextInitialized(ServletContextEvent sce) {
System.err.println("inside context initialized");
scheduler=Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new SomeHourlyJob(), 0, 2, TimeUnit.MINUTES);
}
}
Below is the class which contains static
block.
public class ConnectionUtil {
public static String baseUrl,tokenUrl,grantType,scope,user,password,skillName, accessToken,filePath;
static
{
try {
ClassLoader classLoader= Thread.currentThread().getContextClassLoader();
InputStream input =classLoader.getResourceAsStream("com/dynamicentity/properties/application.properties");
Properties properties =new Properties();
properties.load(input);
System.out.println("Inside the static block of ConnectionUtil class");
skillName=properties.getProperty("chatbot.skillName");
baseUrl=properties.getProperty("chatbot.baseUrl");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
in entire application only this class has static block. will this static block gets executed as soon as i start server? or i will have to run it somehow?
Class initializer blocks static { ...}
run as a part of the class loading process. Normally classes are loaded on demand, when they are needed. If nothing in your code uses the ConnectionUtil class, it's never loaded, and the initializer block never runs.
Add a static method to ConnectionUtil and call it from BaclkgroundJobManager. The method doesn't have to do anything, but having it will ensure that the class gets loaded.
Another possibility is to load the class using the reflection API
Class.forName("your.package.name.ConnectionUtil");