# AOP

## 1. AOP

## 1.1 Two Main Problems

* Code Tangling:
* * For a given method： addAccount(...)
  * We have logging and security code tangled in
* Code Scattering
* * If we need to change logging or security code
  * We have to update All classes

## 1.2 Aspect-Oriented Programming

* Programming technique based on concept of an Aspect
* Aspect encapsulate **cross-cutting concerns**
* "Concern" means logic/functionality

## 1.3 Aspects

* Aspect can be reused at multiple locations
* Same aspect/class ... applied based on configuration&#x20;

## 1.4 Benefits of AOP

* Code for Aspect is defined in a single class
* * Much better than being scattered everywhere
  * Promotes code reuse and easier to change
* Business code in your application is cleaner
* * Only applies to business functionality: addAccount
  * Reduces code complexity
* Configurable
* * Based on configuration, apply Aspects selectively to different parts of app
  * No need to make changes to main application code ... very important!

## 1.5 Additional AOP Use Cases

* Most common
* * logging, security, transactions
* Audit logging
* * who, what, when, where
* Exception handling
* * log exception and notify DevOps team via SMS/email
* API Management
* * how many times has a method been called user
  * analytics: what are peak times? what is average load? who is top user?

## 1.6 Advantages and Disadvantages

| Advantages                                 | Disadvantages                                                 |
| ------------------------------------------ | ------------------------------------------------------------- |
| Reusable modules                           | Too many aspects and app flow is hard to follow               |
| Resolve code tangling                      | Minor performance cost for aspect execution(run-time weaving) |
| Resolve code scatter                       |                                                               |
| Applied selectively based on configuration |                                                               |

## 1.7 Terminology

* Aspect: module of code for a cross-cutting concern(logging, security,...)
* Advice: what action is taken and when it should be applied
* Join Point: When to apply code during program execution
* Pointcut: A predicate expression for where advice should be applied

**Advice Types:**

* Before advice
* After finally advice
* After returning advice
* After throwing advice
* Around advice

## 1.8 Two kinds of AOP

### Spring AOP Support

* Spring provides AOP support
* Key component of Spring
* * Security, transactions, caching etc
* Uses **run-time weaving** of aspects

### AspectJ

* Original AOP framework, released in 2001
* Provides complete support for AOP
* Rich support for&#x20;
* * join points: method-level, constructor, field
  * code weaving: compile-time, post compile-time and load-time

**Spring AOP VS AspectJ:**

| Spring AOP                                                                        | AspectJ                                                                                                 |
| --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| Implemented in pure Java                                                          | Implemented using extensions of Java programming language                                               |
| No need for separate compilation process                                          | Needs AspectJ compiler (ajc) unless LTW is set up                                                       |
| Only runtime weaving is available                                                 | Runtime weaving is not available. Supports compile-time, post-compile, and load-time Weaving            |
| Less Powerful – only supports method level weaving                                | More Powerful – can weave fields, methods, constructors, static initializers, final class/methods, etc… |
| Can only be implemented on beans managed by Spring container                      | Can be implemented on all domain objects                                                                |
| Supports only method execution pointcuts                                          | Support all pointcuts                                                                                   |
| Proxies are created of targeted objects, and aspects are applied on these proxies | Aspects are weaved directly into code before application is executed (before runtime)                   |
| Much slower than AspectJ                                                          | Better Performance                                                                                      |
| Easy to learn and apply                                                           | Comparatively more complicated than Spring AOP                                                          |

* Spring AOP is a light implementation of AOP
* Solves common problems in enterprise applications

Start with Spring AOP ... easy to get started with, if you have complex requirements then move to AspectJ.

### 1.9 Spring AOP Roadmap

* Create Aspects
* Develop Advices
* * Before, After returning, After throwing
  * After finally, Around
* Create Pointcut expressions
* Apply it to our big CRM project (Spring MVC + Hibernate)

## 2. AOP: Pointcut

An **aspect** is a modularization of a concern that cuts across multiple classes. Unified logging can be an example of such cross-cutting concern.

**A&#x20;*****Joinpoint*****&#x20;is a point during the execution of a program, such as execution of a method or the handling of an exception.**

In Spring AOP, a \_JoinPoint \_always represents a method execution.

A **Pointcut** is a predicate that helps match an *Advice \_to be applied by an \_Aspect \_at a particular\_JoinPoint*.

The Advice is often associated with a Pointcut expression and runs at any Joinpoint matched by the Pointcut.

An **advice** is an action taken by an aspect at a particular *Joinpoint*. Different types of advice includ&#x65;*“around”, “before” and* “after” advice.

In Spring, an *Advice is modeled as an interceptor, maintaining a chain of interceptors around the Joinpoint*.

## 2.1 execution pointcuts

* Applies to execution of methods

execution(modifiers-pattern? return-type-pattern declaring-type-pattern? method-name-pattern(param-pattern) throws-pattern?)

* modifiers-pattern: (Spring AOP only supports public or  \*)
* The pattern is optional if it has "?"
* For the patterns, can use wildcard: \* (matches on everything)

## 3.Add AOP logging to this project

## 3.1. Step

1. Add AspectJ Jar file to web project
2. Enable AspectJ Auto Proxy
3. Create Aspect
4. Add logging support
5. Setup pointcut delclarations
6. Add @Before advice
7. Add @AfterReturning advice


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lin-4.gitbook.io/java-ee-notebook/aop.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
