我在下课时创建了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(), 0, 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());
}
}在整个应用程序中,只有这个类具有静态块。一旦我启动服务器,这个静态块会被执行吗?不然我就得管它了?
发布于 2020-08-10 23:49:21
类初始化程序阻止static { ...}作为类加载过程的一部分运行。通常,当需要类时,会按需加载类。如果代码中没有任何内容使用ConnectionUtil类,则它从未加载,初始化程序块也从未运行。
向ConnectionUtil添加一个静态方法并从BaclkgroundJobManager调用它。该方法不需要做任何事情,但是拥有它将确保类被加载。
另一种可能是使用反射API加载类。
Class.forName("your.package.name.ConnectionUtil");https://stackoverflow.com/questions/63349191
复制相似问题