自己写一个实现ApplicationListener​接口并且把该组件加入到容器中

@Component
public class LeonApplicationListener implements ApplicationListener {
    //接受到消息,回调该方法
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        System.out.println("LeonApplicationListener 接受到了一个事件"+event);
    }
}

    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfig.class);
        //手动发布一个事件
        ctx.publishEvent(new ApplicationEvent("我手动发布了一个事件") {
            @Override
            public Object getSource() {
                return super.getSource();
            }
        });
        
        //容器关闭也发布事件
        ctx.close();
    }

测试结果:
LeonApplicationListener 接受到了一个事件org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@37bba400 hierarchy]
LeonApplicationListener 接受到了一个事件com.Leon.testapplicationlistener.MainClass$1[source=我手动发布了一个事件]
LeonApplicationListener 接受到了一个事件org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@37bba400 hierarchy]
    

在Java,`ApplicationListener`接口用于监听特定类型的事件,如`ApplicationEvent`。要实现这个接口,首先你需要创建一个类并实现`ApplicationListener`的抽象方法`onApplicationEvent()`。下面是一个简单的示例: ```java import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class CustomAppListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("ServletContext initialized: " + sce.getServletContext().getServletContextName()); // 在这里添加初始化时需要执行的代码 } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("ServletContext destroyed"); // 在这里添加应用程序销毁时需要执行的清理操作 } @PostConstruct public void init() { // 这里可以执行一些额外的初始化操作 } @PreDestroy public void destroy() { // 这里可以执行应用程序关闭前的清理操作 } } ``` 在这个例子,`contextInitialized()`方法会在应用程序上下文初始化时调用,`contextDestroyed()`则在应用程序上下文关闭时触发。`@PostConstruct`和`@PreDestroy`是JSR-250注解,用于标记构造器完成后的初始化操作和对象销毁前的操作。 要让这个监听器生效,你需要在`web.xml`文件注册它,如下所示: ```xml <listener> <listener-class>com.example.CustomAppListener</listener-class> </listener> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值