问题描述
我在下面的类中创建了ServletContextListener。另外,我在同一包的另一个类中创建了静态块。它将首先在servlet类型的应用程序中运行。该静态块根本没有运行。
@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(),2,TimeUnit.MINUTES);
}
}
下面是包含static
块的类。
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());
}
}
在整个应用程序中,只有此类具有静态块。启动服务器后,此静态块将立即执行吗?还是我必须以某种方式运行它?
解决方法
类初始化程序块static { ...}
在类加载过程中运行。通常,在需要时按需加载类。如果您的代码中没有任何东西使用ConnectionUtil类,则永远不会加载它,并且初始化程序块也永远不会运行。
向ConnectionUtil添加静态方法,然后从BaclkgroundJobManager调用它。该方法无需执行任何操作,但是可以确保该类被加载。
另一种可能性是使用反射API加载类
Class.forName("your.package.name.ConnectionUtil");