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 初始化时执行的代码");
    }
}
相关推荐
醍醐三叶26 分钟前
C++类与对象--2 对象的初始化和清理
开发语言·c++
weixin_4723394627 分钟前
Maven 下载安装与配置教程
java·maven
Magnum Lehar1 小时前
3d游戏引擎EngineTest的系统实现3
java·开发语言·游戏引擎
就叫飞六吧2 小时前
Spring Security 集成指南:避免 CORS 跨域问题
java·后端·spring
Mcworld8572 小时前
java集合
java·开发语言·windows
成功人chen某2 小时前
配置VScodePython环境Python was not found;
开发语言·python
天黑请闭眼2 小时前
IDEA:程序编译报错:java: Compilation failed: internal java compiler error
java·intellij-idea
海绵宝宝贾克斯儿3 小时前
C++中如何实现一个单例模式?
开发语言·c++·单例模式
史迪仔01123 小时前
[python] Python单例模式:__new__与线程安全解析
开发语言·python·单例模式
苍煜3 小时前
Maven构建流程详解:如何正确管理微服务间的依赖关系-当依赖的模块更新后,我应该如何重新构建主项目
java·微服务·maven