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 初始化时执行的代码");
    }
}
相关推荐
写bug写bug8 分钟前
搞懂Spring任务执行器和调度器模型
java·后端·spring
熊猫片沃子21 分钟前
Maven在使用过程中的核心知识点总结
java·后端·maven
都叫我大帅哥22 分钟前
🌊 限流算法百科全书:从原理到实践,一篇搞定高并发流量管控
java·算法
Gu_shiwww23 分钟前
数据结构2线性表——顺序表
c语言·开发语言·数据结构·python
tanxiaomi24 分钟前
✨ 基于 JsonSerialize 实现接口返回数据的智能枚举转换(优雅告别前端硬编码!)
java·前端·spring·spring cloud·mybatis
要做朋鱼燕39 分钟前
理清C语言中内存操作的函数
c语言·开发语言
星你1 小时前
用Spring Boot 搭建自己的 MCP Server
java·后端
Volunteer Technology2 小时前
Lua基础+Lua数据类型
开发语言·junit·lua
回家路上绕了弯2 小时前
深度理解 volatile 与 synchronized:并发编程的两把钥匙
java·后端
程序员清风2 小时前
ThreadLocal在什么情况下会导OOM?
java·后端·面试