java项目启动时,执行某方法

1. J2EE项目

在Servlet类中重写init()方法,这个方法会在Servlet实例化时调用,即项目启动时调用。

复制代码
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

public class MyServlet extends HttpServlet {

    @Override
    public void init() throws ServletException {
        super.init();
        // 在项目启动时执行的代码
        System.out.println("Servlet 初始化时执行的代码");
    }
}

配置web.xml

web.xml文件中配置Servlet,以确保它在项目启动时加载。

复制代码
<servlet>
    <servlet-name>myServlet</servlet-name>
    <servlet-class>com.example.MyServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<load-on-startup>元素的值为1,表示Servlet将在项目启动时加载。

2. Spring框架,使用@PostConstruct注解

复制代码
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;

@Component
public class MyComponent {

    @PostConstruct
    public void init() {
        // 在项目启动时执行的代码
        System.out.println("Spring @PostConstruct 初始化时执行的代码");
    }
}

3. Spring框架,使用ApplicationListener接口

Spring的ApplicationListener接口允许我们监听Spring应用上下文的启动事件,从而在项目启动时执行代码。

复制代码
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 在项目启动时执行的代码
        System.out.println("Spring ApplicationListener 初始化时执行的代码");
    }
}

4. Spring框架,实现CommandLineRunner或ApplicationRunner接口

实现CommandLineRunner接口,并重写run方法。

复制代码
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyCommandLineRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        // 在项目启动时执行的代码
        System.out.println("Spring CommandLineRunner 初始化时执行的代码");
    }
}

实现ApplicationRunner接口,并重写run方法。

复制代码
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.ApplicationArguments;
import org.springframework.stereotype.Component;

@Component
public class MyApplicationRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 在项目启动时执行的代码
        System.out.println("Spring ApplicationRunner 初始化时执行的代码");
    }
}
相关推荐
Kali_075 分钟前
使用 Mathematical_Expression 从零开始实现数学题目的作答小游戏【可复制代码】
java·人工智能·免费
rzl0217 分钟前
java web5(黑马)
java·开发语言·前端
jingling55529 分钟前
面试版-前端开发核心知识
开发语言·前端·javascript·vue.js·面试·前端框架
guojl36 分钟前
深度解读jdk8 HashMap设计与源码
java
guojl41 分钟前
深度解读jdk8 ConcurrentHashMap设计与源码
java
m0_687399841 小时前
写一个Ununtu C++ 程序,调用ffmpeg API, 来判断一个数字电影的视频文件mxf 是不是Jpeg2000?
开发语言·c++·ffmpeg
爱上语文1 小时前
Redis基础(5):Redis的Java客户端
java·开发语言·数据库·redis·后端
A~taoker1 小时前
taoker的项目维护(ng服务器)
java·开发语言
萧曵 丶1 小时前
Rust 中的返回类型
开发语言·后端·rust
HGW6891 小时前
基于 Elasticsearch 实现地图点聚合
java·elasticsearch·高德地图