Topic 13: – 3 sections of Advanced Spring Boot Topics

Play Store Application link – Spring Boot in 13 steps – App on Google Play

In this guide, we will explore some advanced Spring Boot concepts: event handling, asynchronous processing, and scheduled tasks. Each topic will be presented with practical code examples to help you implement these features in your Spring Boot applications.


Github project link – I want you to implement these features just like I’ve already done for the other Spring Boot features. If you run into any problems or get stuck, just drop a comment below

Step 1: Setting Up a Spring Boot Project

Using Spring Initializr

  1. Visit https://start.spring.io/.
  2. Configure the project:
    • Project: Maven
    • Language: Java
    • Spring Boot Version: 3.x.x
    • Dependencies: Spring Web, Spring Boot DevTools
  3. Click Generate to download the project ZIP and extract it.

Import into IDE

  • Import the project into your favorite IDE (IntelliJ, Eclipse, etc.) as a Maven project.

Part 1: Event Handling in Spring Boot

Using ApplicationEventPublisher and Custom Events

Step 1: Create a Custom Event
package com.example.advancedtopics.event;
import org.springframework.context.ApplicationEvent;
public class CustomEvent extends ApplicationEvent {
    private String message;
    public CustomEvent(Object source, String message) {
        super(source);
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
}

Step 2: Publish Custom Event
package com.example.advancedtopics.service;
import com.example.advancedtopics.event.CustomEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
@Service
public class EventPublisherService {
    private final ApplicationEventPublisher eventPublisher;
    public EventPublisherService(ApplicationEventPublisher eventPublisher) {
        this.eventPublisher = eventPublisher;
    }
    public void publishEvent(String message) {
        CustomEvent event = new CustomEvent(this, message);
        eventPublisher.publishEvent(event);
    }
}

Step 3: Create an Event Listener
package com.example.advancedtopics.listener;
import com.example.advancedtopics.event.CustomEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class CustomEventListener implements ApplicationListener<CustomEvent> {
    @Override
    public void onApplicationEvent(CustomEvent event) {
        System.out.println("Event received with message: " + event.getMessage());
    }
}

Step 4: Testing the Event

Create a REST controller to trigger the event:

package com.example.advancedtopics.controller;
import com.example.advancedtopics.service.EventPublisherService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EventController {
    private final EventPublisherService eventPublisherService;
    public EventController(EventPublisherService eventPublisherService) {
        this.eventPublisherService = eventPublisherService;
    }
    @GetMapping("/trigger-event")
    public String triggerEvent() {
        eventPublisherService.publishEvent("Hello, this is a custom event!");
        return "Event triggered!";
    }
}


Part 2: Asynchronous Processing

Implementing Asynchronous Methods with @Async

Step 1: Enable Asynchronous Processing

Add @EnableAsync in your main application class:

package com.example.advancedtopics;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync
public class AdvancedTopicsApplication {
    public static void main(String[] args) {
        SpringApplication.run(AdvancedTopicsApplication.class, args);
    }
}

Step 2: Create an Asynchronous Service
package com.example.advancedtopics.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
    @Async
    public void performTask() {
        try {
            System.out.println("Task started in thread: " + Thread.currentThread().getName());
            Thread.sleep(5000); // Simulate delay
            System.out.println("Task completed in thread: " + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Step 3: Testing the Asynchronous Task

Create a REST controller to trigger the asynchronous method:

package com.example.advancedtopics.controller;
import com.example.advancedtopics.service.AsyncService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AsyncController {
    private final AsyncService asyncService;
    public AsyncController(AsyncService asyncService) {
        this.asyncService = asyncService;
    }
    @GetMapping("/perform-task")
    public String performTask() {
        asyncService.performTask();
        return "Task is being processed asynchronously!";
    }
}

Configuring Thread Pools for Better Performance

You can configure thread pools for asynchronous tasks by adding the following configuration:

package com.example.advancedtopics.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
public class AsyncConfig {
    @Bean
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(25);
        executor.setThreadNamePrefix("async-task-");
        executor.initialize();
        return executor;
    }
}


Part 3: Scheduled Tasks

Creating Scheduled Jobs with @Scheduled

Step 1: Enable Scheduling

Add @EnableScheduling in your main application class:

package com.example.advancedtopics;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class AdvancedTopicsApplication {
    public static void main(String[] args) {
        SpringApplication.run(AdvancedTopicsApplication.class, args);
    }
}

Step 2: Create a Scheduled Task
package com.example.advancedtopics.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class ScheduledService {
    @Scheduled(fixedRate = 5000) // Executes every 5 seconds
    public void performScheduledTask() {
        System.out.println("Scheduled task running at: " + System.currentTimeMillis());
    }
}

Advanced Scheduling with Cron Expressions

You can also use cron expressions for more complex scheduling:

package com.example.advancedtopics.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class CronScheduledService {
    @Scheduled(cron = "0 0 12 * * ?") // Executes at 12 PM every day
    public void performCronTask() {
        System.out.println("Cron task running at: " + System.currentTimeMillis());
    }
}


Conclusion

In this guide, we covered advanced Spring Boot topics including:

  1. Event Handling: Creating and listening for custom events using ApplicationEventPublisher and @EventListener.
  2. Asynchronous Processing: Using @Async for running methods asynchronously and configuring thread pools.
  3. Scheduled Tasks: Running scheduled jobs using @Scheduled and advanced scheduling with cron expressions.

7 comments

  1. Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?

  2. I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.

  3. Your point of view caught my eye and was very interesting. Thanks. I have a question for you.

Leave a Reply

Your email address will not be published. Required fields are marked *