DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Effective Microservices CI/CD With GitHub Actions and Ballerina
  • Automate Web Portal Deployment in Minutes Using GitHub Actions
  • How GitHub Codespaces Helps in Reducing Development Setup Time
  • How To Build a Simple GitHub Action To Deploy a Django Application to the Cloud

Trending

  • Customer 360: Fraud Detection in Fintech With PySpark and ML
  • My LLM Journey as a Software Engineer Exploring a New Domain
  • Unlocking the Benefits of a Private API in AWS API Gateway
  • Understanding and Mitigating IP Spoofing Attacks
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. Handling Exceptions Using Spring's AOP

Handling Exceptions Using Spring's AOP

This quick lesson in AOP will explore you can use Spring's implementation of aspect-oriented programming to handle exceptions.

By 
Mir Md Asif Hossain user avatar
Mir Md Asif Hossain
·
Jan. 31, 18 · Tutorial
Likes (15)
Comment
Save
Tweet
Share
74.7K Views

Join the DZone community and get the full member experience.

Join For Free

In this post, I will show you how we can handle exceptions using Spring's aspect-oriented programming.

Prerequisites

To follow this article, you should have:

  • JDK 8+  
  • Gradle 2.3 + 
  • Your favorite IDE (I use IntelliJ IDEA)

Folder Structure

The folder structure should be as follows.

aopexceptionhandling:

├── build.gradle
└── src    
        ├── main    
        │   └── java
        │       └── net    
        │           └── asifhossain    
        │               └── aopexceptionhandling    
        │                   ├── aop    
        │                   │   └── ExceptionLoggerPointCut.java    
        │                   ├── AopExampleApp.java    
        │                   └── service    
        │                       └── ExceptionalService.java    
        └── test        
                └── java            
                         └── net                
                             └── asifhossain
                                 └── aopexceptionhandling
                                    └── AopExampleAppTest.java


Creating a Gradle Build File

Create a file named build.gradle in the application with the following content:

build.gradle:

group 'net.asifhossain'

buildscript {
    ext {
        springBootVersion = '1.5.9.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'net.asifhossain'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-aop')
    compile('org.springframework.boot:spring-boot-starter-web')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}


Creating the Service

Now let's create a service method that will throw an exception.

ExceptionalService.java:

package net.asifhossain.aopexceptionhandling.service;

import org.springframework.stereotype.Service;

@Service
public class ExceptionalService {
    public void throwException() throws Exception {
        throw new Exception();
    }
}


Now let's create an aspect configuration file to log all the exceptions thrown from the service method.

ExceptionLoggerPointCut.java:

package net.asifhossain.aopexceptionhandling.aop;

import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;

@Configuration
@Aspect
public class ExceptionLoggerPointCut {
    @AfterThrowing(pointcut = "execution(* net.asifhossain.aopexceptionhandling.*.*.*(..))", throwing = "ex")
    public void logError(Exception ex) {
        ex.printStackTrace();
    }
}


Making the Application Runnable

Now create the application class with all the components.

AopExampleApp.java:

package net.asifhossain.aopexceptionhandling;

import net.asifhossain.aopexceptionhandling.service.ExceptionalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@SpringBootApplication
@EnableAspectJAutoProxy
public class AopExampleApp implements CommandLineRunner {

    @Autowired
    ExceptionalService service;

    @Override
    public void run(String... args) throws Exception {
        try {
            service.throwException();
        } catch (Exception ex) {
            
        }
    }

    public static void main(String[] args) {
        SpringApplication.run(AopExampleApp.class);
    }
}


Running the Application

To run the application, run the following command:

gradle bootRun 

You will see the thrown exception is logged on the console.

You can find all the codes in my GitHub repository.

That's all for today. Thanks for reading.

application intellij Gradle Java Development Kit Console (video game CLI) GitHub Repository (version control)

Published at DZone with permission of Mir Md Asif Hossain. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Effective Microservices CI/CD With GitHub Actions and Ballerina
  • Automate Web Portal Deployment in Minutes Using GitHub Actions
  • How GitHub Codespaces Helps in Reducing Development Setup Time
  • How To Build a Simple GitHub Action To Deploy a Django Application to the Cloud

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!