Guía simple de AOP en Spring Boot

Guía práctica de AOP en Spring Boot: qué es @Aspect, cómo habilitarlo, crear aspectos y usar Before, After y Around, con anotaciones personalizadas y buenas prácticas.

26 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Guía simple de AOP en Spring Boot: una introducción práctica a aspectos y anotaciones para añadir comportamientos transversales sin mezclar lógica de negocio

Qué es la anotación @Aspect: en Spring AOP la anotación @Aspect identifica una clase como aspecto dentro de la programación orientada a aspectos. Un aspecto encapsula comportamientos transversales como logging, auditoría o gestión de excepciones que se ejecutan cuando coinciden criterios definidos, por ejemplo cuando se invoca un método concreto o cuando un método lleva una anotación personalizada.

Por qué es importante: separar responsabilidades permite mantener la lógica de negocio limpia y centrada en su propósito; la reutilización facilita aplicar una misma funcionalidad en muchos puntos de la aplicación desde un único lugar; y el mantenimiento mejora al centralizar cambios en aspectos como logging, métricas o seguridad.

Dependencias: añadir soporte AOP en un proyecto Spring Boot requiere el starter correspondiente. Ejemplo Maven: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>

Paso 1 Habilitar AOP: en la configuración de Spring se activa con la anotación @EnableAspectJAutoProxy. Ejemplo de clase de configuración: import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @Configuration @EnableAspectJAutoProxy public class AppConfig { }

Paso 2 Crear la clase aspecto: definir una clase anotada con @Aspect y típicamente también con @Component para que Spring la gestione. Ejemplo resumido: import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; @Aspect @Component public class LoggingAspect { private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(LoggingAspect.class); }

Paso 3 Definir los comportamientos cuando se cumplen los criterios: ejemplos comunes

Before: ejecutar lógica antes de un método. Ejemplo de aspecto simplificado: @Before(execution(* org.spring.mastery.service.TestService.testBefore(..))) public void logBeforeMethod() { logger.info(A method is about to be executed!); }

After: ejecutar lógica después de la ejecución de un método. Ejemplo: @After(execution(* org.spring.mastery.service.TestService.testAfter(..))) public void logAfterMethod() { logger.info(A method has just finished success or error.); }

AfterReturning: detectar el valor devuelto por un método y capturarlo. Ejemplo: @AfterReturning(pointcut = execution(* org.spring.mastery.service.TestService.testAfterReturning(..)), returning = result) public void logAfterReturning(Object result) { logger.info(Method returned value: {} , result); }

AfterThrowing: ejecutar lógica cuando un método lanza una excepción. Ejemplo: @AfterThrowing(pointcut = execution(* org.spring.mastery.service.TestService.testAfterThrowing(..)), throwing = ex) public void logAfterThrowing(Exception ex) { logger.error(Method threw exception: {} , ex.getMessage()); }

Around: envolver la ejecución del método para ejecutar código antes y después y controlar la invocación. Ejemplo resumido: @Around(execution(* org.spring.mastery.service.TestService.testAround(..))) public Object logAround(org.aspectj.lang.ProceedingJoinPoint joinPoint) throws Throwable { logger.info([Around] Before: {} , joinPoint.getSignature()); Object result = joinPoint.proceed(); logger.info([Around] After: {} , joinPoint.getSignature()); return result; }

Anotaciones personalizadas: en lugar de usar rutas de paquete en pointcuts puedes crear una anotación propia y aplicarla a métodos. Ejemplo de anotación: import java.lang.annotation.*; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Auditable { } y luego detectar la anotación desde el aspecto: @Before(@annotation(com.example.aop.Auditable)) public void audit() { logger.info(Auditing action…); } De este modo puedes reutilizar la anotación en tantos métodos como necesites.

Buenas prácticas y precauciones: mantener una estructura de paquetes clara porque cambios en nombres de paquetes o clases pueden romper pointcuts basados en rutas; documentar qué aspectos existen y qué comportamientos añaden para facilitar el mantenimiento; evitar lógica de negocio compleja dentro de aspectos y preferir aspectos ligeros orientados a transversalidad.

Sobre Q2BSTUDIO: en Q2BSTUDIO somos una empresa de desarrollo de software y aplicaciones a medida especializada en soluciones integrales que incluyen software a medida, inteligencia artificial aplicada a empresas, ciberseguridad y servicios cloud. Ofrecemos servicios de desarrollo de aplicaciones multiplataforma y proyectos a medida, y podemos ayudarte a integrar AOP en tus aplicaciones para mejorar trazabilidad y mantenimiento. Con experiencia en servicios cloud aws y azure y en servicios de inteligencia de negocio, trabajamos para que tus soluciones escalen y sean seguras. Conoce nuestro enfoque en desarrollo de aplicaciones a medida visitando desarrollo de aplicaciones a medida y descubre nuestros servicios de inteligencia artificial en servicios de inteligencia artificial.

Palabras clave: aplicaciones a medida, software a medida, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA, power bi.

Conclusión: AOP en Spring Boot es una herramienta poderosa para añadir comportamientos transversales sin contaminar la lógica de negocio. Úsala con criterio, documenta tus aspectos y aprovecha la experiencia de equipos expertos como Q2BSTUDIO para integrar seguridad, cloud e inteligencia de negocio en tus proyectos.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat