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 初始化时执行的代码");
    }
}
相关推荐
木昜先生几秒前
知识点:深入理解 JVM 内存管理与垃圾回收
java·jvm·后端
115432031q4 分钟前
基于SpringBoot+Vue实现的旅游景点预约平台功能十三
java·前端·后端
战族狼魂7 分钟前
基于SpringBoot+PostgreSQL+ROS Java库机器人数据可视化管理系统
java·spring boot·postgresql
半个脑袋儿14 分钟前
Java线程控制: sleep、yield、join深度解析
java
猫猫头有亿点炸18 分钟前
C语言大写转小写2.0
c语言·开发语言
小智疯狂敲代码18 分钟前
Spring MVC-DispatcherServlet 的源码解析
java·面试
int0x0319 分钟前
Java中的内存"瘦身术":揭秘String Deduplication
java
半个脑袋儿20 分钟前
Java日期格式化中的“YYYY”陷阱:为什么跨年周会让你的年份突然+1?
java·后端
A达峰绮27 分钟前
设计一个新能源汽车控制系统开发框架,并提供一个符合ISO 26262标准的模块化设计方案。
大数据·开发语言·经验分享·新能源汽车
CHQIUU33 分钟前
Java 设计模式心法之第25篇 - 中介者 (Mediator) - 用“中央协调”降低对象间耦合度
java·设计模式·中介者模式