java - ServletContextListener 和静态块
问题描述
我在下面的类中创建了 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());
}
}
在整个应用程序中,只有此类具有静态块。这个静态块会在我启动服务器后立即执行吗?或者我将不得不以某种方式运行它?
解决方案
类初始化程序块static { ...}
作为类加载过程的一部分运行。通常,类在需要时按需加载。如果您的代码中没有任何内容使用 ConnectionUtil 类,则它永远不会加载,并且初始化程序块永远不会运行。
将静态方法添加到 ConnectionUtil 并从 BaclkgroundJobManager 调用它。该方法不必做任何事情,但是拥有它可以确保类被加载。
另一种可能性是使用反射 API 加载类
Class.forName("your.package.name.ConnectionUtil");
推荐阅读
- typo3 - 在 Typo3 中为 Mask-Elements 设置后端标题
- elixir - 迁移数据库约束
- python - 在循环网络上使用预训练的句子嵌入
- symfony - 教义 find() 和 querybuilder() 在 PHPUnit 测试中返回不同的结果
- android-studio - Flutter build.gradle 麻烦
- jdbc - 无法使用 Java JDBC 从 AWS EMR 上的 Presto 连接/查询
- javascript - 已声明标识符 - 已声明标识符“userScore”
- javascript - 在 req.user.save() 后表示不保存
- css - 是否可以使表格的前两列与其内容一样宽,而第三列占据剩余空间?
- java - 将我的文件复制到目录中的问题