search
HomeJavajavaTutorialHow to start a listening thread to perform tasks in springboot

    springboot starts a listening thread to perform tasks

    public class StartApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
    
        @Override
        public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
            ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
            ApplicationContext parent = applicationContext.getParent();
            if (parent == null) {
                CacheManager cacheManager = applicationContext.getBean(CacheManager.class);
                Cache cache = cacheManager.getCache(MsConstants.NODE_CACHE_NAME);
               new Thread(new Runnable() {
                   @Override
                   public void run() {
                      //代码
                     
                   }
               }).start();
            }
        }
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(FigureServerApplication.class);
        app.addListeners(new StartApplicationListener());
        app.run(args);
    }

    Creation process of listening events in springboot

    In the Spring Boot project, you can Use the annotation @Async to implement asynchronous processing, and event listening has two methods: synchronous and asynchronous.

    General steps of events

    • 1: Define an event.

    • 2: Create a listener.

    • 3: Make sure the listener is inside the container.

    • 4: Publish the event for testing.

    Without further ado, let’s briefly describe the demos of several different methods.

    First, we create a springboot project.

    First type

    1: Define an event and need to inherit ApplicationEvent

    public class MyEvent extends ApplicationEvent {
        public MyEvent(Object source) {
            super(source);
            System.out.println("我是一个事件,目前在事件的构造器内");
        }
    }

    2: Create a listener. Directly implement the ApplicationListener interface and rewrite the onApplicationEvent method.

    public class MyEventListener implements ApplicationListener<MyEvent> {
        @Override
        public void onApplicationEvent(MyEvent event) {
            System.out.println("现在开始执行监听器中的内容,我是直接实现ApplicationListener接口的方式进行的");
            System.out.println("event.getSource() = " + event.getSource());
        }
    }

    3: Manually add the listener to the application container and publish the event.

    @SpringBootApplication
    public class EventTestApplication {
        public static void main(String[] args) {
    //        SpringApplication.run(EventTestApplication.class, args);
            //第一种:自己手动将监听器添加到application中
            SpringApplication application = new SpringApplication(EventTestApplication.class);
            //添加监听器
            application.addListeners(new MyEventListener());
            ConfigurableApplicationContext context = application.run(args);
            //进行发布事件
            context.publishEvent(new MyEvent("Event数据源"));
            context.close();
        }
    }

    4: Start the main startup class and perform printing tests.

    Second type

    1: Same as the first type 1

    2: Create a listener.

    /**
     *第二种:打上Compoent注解,  将事件监听器自动加入到应用容器中
     * 这种方式不需要手动加入到容器中。
     * */
    @Component
    public class MyEventListener2 implements ApplicationListener<MyEvent> {
        @Override
        public void onApplicationEvent(MyEvent event) {
            System.out.println("现在开始执行监听器中的内容,我是打Compoent注解的方式进行的");
            System.out.println("event.getSource() = " + event.getSource());
        }
    }

    3: Publish the event and then perform startup class testing.

    @SpringBootApplication
    public class EventTestApplication {
        public static void main(String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(EventTestApplication.class, args);
            //发布事件
            context.publishEvent(new MyEvent("source"));
            context.close();
        }
    }

    The third type

    all use annotations

    1: Same as the first type 1

    2: Create A listener.

    /**
     *第三种:采用@EventListener注解的方式,不需要在类上实现ApplicationListener接口。
     * 直接采用的是通过注解,将方法标识为一个监听器。
     * */
    @Component
    public class MyEventListener3 {
        @Async//异步注解。开启一个新线程。 去掉此注解则会变成同步监听。
        @EventListener(classes = MyEvent.class)
        public void TestListener(MyEvent myEvent){
            System.out.println("我是@EventListener注解的方式实现的监听器");
            System.out.println("myEvent.getSource() = " + myEvent.getSource());
        }
    }

    3: Publish the event and then perform startup class testing.

    @SpringBootApplication
    public class EventTestApplication {
        public static void main(String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(EventTestApplication.class, args);
            //发布事件
            context.publishEvent(new MyEvent("source"));
            context.close();
        }
    }

    The following is the structure diagram of the code:

    How to start a listening thread to perform tasks in springboot

    The above is the detailed content of How to start a listening thread to perform tasks in springboot. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

    The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

    How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

    The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

    How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

    The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

    How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

    The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

    How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

    Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment