ServletContextListener 和静态块

ServletContextListener and static block

我在下面 class 创建了 ServletContextListener。我还在同一包的另一个 class 中创建了静态块。这将 运行 首先出现在 servlet 类型的应用程序中。该静态块根本不是 运行ning。

@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 块的 class。

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());
       }
        
    }

在整个应用程序中只有这个 class 有静态块。这个静态块会在我启动服务器后立即执行吗?或者我将不得不 运行 它以某种方式?

Class 初始化块 static { ...} 运行 作为 class 加载过程的一部分。通常 classes 在需要时按需加载。如果您的代码中没有任何内容使用 ConnectionUtil class,则它永远不会加载,并且初始化程序块永远不会 运行s.

向 ConnectionUtil 添加静态方法并从 BaclkgroundJobManager 调用它。该方法不必执行任何操作,但拥有它可以确保 class 被加载。

另一种可能性是使用反射 API

加载 class
Class.forName("your.package.name.ConnectionUtil");