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 初始化时执行的代码");
    }
}
相关推荐
皮皮林5518 小时前
IDEA 源码阅读利器,你居然还不会?
java·intellij idea
卡尔特斯12 小时前
Android Kotlin 项目代理配置【详细步骤(可选)】
android·java·kotlin
白鲸开源12 小时前
Ubuntu 22 下 DolphinScheduler 3.x 伪集群部署实录
java·ubuntu·开源
ytadpole12 小时前
Java 25 新特性 更简洁、更高效、更现代
java·后端
纪莫12 小时前
A公司一面:类加载的过程是怎么样的? 双亲委派的优点和缺点? 产生fullGC的情况有哪些? spring的动态代理有哪些?区别是什么? 如何排查CPU使用率过高?
java·java面试⑧股
JavaGuide13 小时前
JDK 25(长期支持版) 发布,新特性解读!
java·后端
用户37215742613513 小时前
Java 轻松批量替换 Word 文档文字内容
java
白鲸开源13 小时前
教你数分钟内创建并运行一个 DolphinScheduler Workflow!
java
Java中文社群14 小时前
有点意思!Java8后最有用新特性排行榜!
java·后端·面试
代码匠心14 小时前
从零开始学Flink:数据源
java·大数据·后端·flink