| 1 |
------ |
| 2 |
AspectJ in a multi-module reactor |
| 3 |
------ |
| 4 |
------ |
| 5 |
------ |
| 6 |
|
| 7 |
Strategies for using AspectJ in a Maven multi-module reactor |
| 8 |
|
| 9 |
In a multi-module reactor, a convenient pattern for using AspectJ is to create one project containing Aspect |
| 10 |
definitions to be used by ("woven into") the code of other projects within the Maven reactor. Since |
| 11 |
some dependencies (such as the AspectJ runtime) must be identical in all of the projects within |
| 12 |
the Maven reactor, this walkthrough serves as a step-by-step guide to painless use of aspects in a |
| 13 |
multi-module reactor. |
| 14 |
|
| 15 |
To make this walkthrough less abstract, we will use Validation as an example throughout the step-by-step guide. |
| 16 |
In this example, we will create a small API for validating the internal state of objects, and delegate its |
| 17 |
correct use to AspectJ by means of the AspectJ Maven Plugin. There are many ways besides AspectJ to perform |
| 18 |
this, but AspectJ is one of the few which does not depend on particular surroundings such as containers or |
| 19 |
application servers. In fact, the small Validation solution may be run directly in a plain Java SE environment. |
| 20 |
All steps will be detailed in the walkthrough below, but we will start by taking a look at the end result: |
| 21 |
|
| 22 |
[../images/plantuml/multimodule_ajc.png] Resulting reactor |
| 23 |
|
| 24 |
The reactor contains the following parts: |
| 25 |
|
| 26 |
* <<rootParentPOM>>: Contains version definitions for the aspectjrt and aspectjtools libraries, to be |
| 27 |
used in all projects in the multi-module reactor. |
| 28 |
|
| 29 |
* <<validation-api>>: Defines a small API for validating the internal state of objects. |
| 30 |
|
| 31 |
* <<validation-aspect>>: Defines an Aspect using classes from the <<<validation-api>>> to validate the |
| 32 |
internal state of objects. |
| 33 |
|
| 34 |
* <<aspectParentPOM>>: Configures the AspectJ Maven Plugin (this plugin!) to use the Aspect defined within |
| 35 |
the <<<validation-aspect>>> project and apply it on all maven projects having the aspectParentPOM for |
| 36 |
parent. |
| 37 |
|
| 38 |
* <<mavenProjectWithAspects>>: A project whose classes can use/implement types from the validation-api to |
| 39 |
indicate that the aspect defined in <<<validation-aspect>>> project should be woven into its bytecode |
| 40 |
representation. |
| 41 |
|
| 42 |
After the introduction, let us proceed to the step-by-step guide. |
| 43 |
|
| 44 |
* 1. Define required runtime dependency versions |
| 45 |
|
| 46 |
In the rootParentPom, define dependencies for the AspectJ runtime and your library holding aspects. |
| 47 |
It is recommended to introduce a Maven property in order to reduce the number of locations where |
| 48 |
the AspectJ version must be changed to upgrade the dependency. |
| 49 |
|
| 50 |
+------------------------------------------ |
| 51 |
<!-- +========================================= --> |
| 52 |
<!-- | Maven property definitions --> |
| 53 |
<!-- +========================================= --> |
| 54 |
<properties> |
| 55 |
<aspectj.runtime.version>1.8.2</aspectj.runtime.version> |
| 56 |
|
| 57 |
... |
| 58 |
</properties> |
| 59 |
|
| 60 |
|
| 61 |
<!-- +========================================= --> |
| 62 |
<!-- | Dependency (management) settings --> |
| 63 |
<!-- +========================================= --> |
| 64 |
<dependencyManagement> |
| 65 |
<dependencies> |
| 66 |
|
| 67 |
<!-- AOP dependencies. --> |
| 68 |
<dependency> |
| 69 |
<groupId>org.aspectj</groupId> |
| 70 |
<artifactId>aspectjrt</artifactId> |
| 71 |
<version>${aspectj.runtime.version}</version> |
| 72 |
</dependency> |
| 73 |
<dependency> |
| 74 |
<groupId>org.aspectj</groupId> |
| 75 |
<artifactId>aspectjtools</artifactId> |
| 76 |
<version>${aspectj.runtime.version}</version> |
| 77 |
</dependency> |
| 78 |
|
| 79 |
... |
| 80 |
|
| 81 |
</dependencies> |
| 82 |
</dependencyManagement> |
| 83 |
|
| 84 |
+------------------------------------------ |
| 85 |
|
| 86 |
The definitions in the rootParentPOM are now complete. |
| 87 |
|
| 88 |
* 2. Implement the Validation-API |
| 89 |
|
| 90 |
For the purpose of this example, we would like AspectJ to enforce a common behaviour/lifecycle for |
| 91 |
objects whose internal state can be validated. The Validation-API contains a defining interface, |
| 92 |
<<<Validatable>>>, which should be implemented by any class whose objects should be validated after |
| 93 |
being created. The Validatable interface is shown below: |
| 94 |
|
| 95 |
+------------------------------------------ |
| 96 |
/** |
| 97 |
* Specification for providing an object with Validation mechanics. |
| 98 |
* Each Validatable object can perform internal validation to assert |
| 99 |
* its state before being serialized and after being deserialized. |
| 100 |
* |
| 101 |
* Making an object implement Validatable does not imply that all |
| 102 |
* uses of the object is guaranteed. Validatable objects should |
| 103 |
* primarily make use of their own data to ascertain its valid state. |
| 104 |
* |
| 105 |
* It is the responsibilities of services using the Validatable object |
| 106 |
* (as opposed to the validation mechanics provided within this Validatable) |
| 107 |
* to provide extra/semantic validation for object <strong>graphs</strong> |
| 108 |
* in which this Validatable instance is part. |
| 109 |
*/ |
| 110 |
public interface Validatable { |
| 111 |
|
| 112 |
/** |
| 113 |
* Performs validation of the internal state of this Validatable. |
| 114 |
* |
| 115 |
* @throws InternalStateValidationException |
| 116 |
* if the state of this Validatable was |
| 117 |
* in an incorrect state (i.e. invalid). |
| 118 |
*/ |
| 119 |
void validateInternalState() throws InternalStateValidationException; |
| 120 |
} |
| 121 |
+------------------------------------------ |
| 122 |
|
| 123 |
Following the definition of a custom exception class called <<<InternalStateValidationException>>> |
| 124 |
which should extends <<<IllegalStateException>>>, the small validation-api project is complete: |
| 125 |
|
| 126 |
+------------------------------------------ |
| 127 |
/** |
| 128 |
* Exception indicating problems occurred when validating a Validatable instance. |
| 129 |
*/ |
| 130 |
public class InternalStateValidationException extends IllegalStateException { |
| 131 |
|
| 132 |
/** |
| 133 |
* Constructs an InternalStateValidationException with the specified detail message. |
| 134 |
* A detail message is a String that describes this particular exception. |
| 135 |
* |
| 136 |
* @param message the String that contains a detailed message |
| 137 |
*/ |
| 138 |
public InternalStateValidationException(final String message) { |
| 139 |
super(message); |
| 140 |
} |
| 141 |
} |
| 142 |
+------------------------------------------ |
| 143 |
|
| 144 |
Assuming that the rootParentPOM contains common build definitions which should be applied to the |
| 145 |
validation-api project, we should remember to assign the rootParentPOM as its parent. |
| 146 |
In this brief example, we explore no reason to connect the validation-api to a parent - but in real life |
| 147 |
configurations such as licensing, coverage, code style, etc. are frequently configured and maintained |
| 148 |
only in one POM - the rootParentPOM. |
| 149 |
|
| 150 |
* 3. Implement the Aspect performing validation |
| 151 |
|
| 152 |
Now that our tiny Validation API is complete, it is time to implement its corresponding Aspect. |
| 153 |
This is done in the <<<validation-aspect>>> project, which must import the validation-api as a |
| 154 |
dependency in its POM. It is also important that the validation-aspect project assigns its POM |
| 155 |
parent to rootParentPOM, since we want to use the AspectJ definitions from the parent. The POM |
| 156 |
bits of the validation-aspect project are shown below: |
| 157 |
|
| 158 |
+------------------------------------------ |
| 159 |
<!-- +========================================= --> |
| 160 |
<!-- | Define the Parent POM --> |
| 161 |
<!-- +========================================= --> |
| 162 |
<parent> |
| 163 |
<groupId>some.group.id</groupId> |
| 164 |
<artifactId>rootParentPOM</artifactId> |
| 165 |
<version>1.0.0-SNAPSHOT</version> |
| 166 |
</parent> |
| 167 |
|
| 168 |
<!-- +========================================= --> |
| 169 |
<!-- | Dependency (management) settings --> |
| 170 |
<!-- +========================================= --> |
| 171 |
<dependencies> |
| 172 |
<dependency> |
| 173 |
<groupId>some.group.id</groupId> |
| 174 |
<artifactId>validation-api</artifactId> |
| 175 |
<version>1.0.0-SNAPSHOT</version> |
| 176 |
</dependency> |
| 177 |
|
| 178 |
<dependency> |
| 179 |
<groupId>org.aspectj</groupId> |
| 180 |
<artifactId>aspectjrt</artifactId> |
| 181 |
<scope>compile</scope> |
| 182 |
</dependency> |
| 183 |
|
| 184 |
... |
| 185 |
</dependencies> |
| 186 |
|
| 187 |
<!-- +========================================= --> |
| 188 |
<!-- | Build settings --> |
| 189 |
<!-- +========================================= --> |
| 190 |
<build> |
| 191 |
<plugins> |
| 192 |
<plugin> |
| 193 |
<groupId>org.codehaus.mojo</groupId> |
| 194 |
<artifactId>aspectj-maven-plugin</artifactId> |
| 195 |
<version>${project.version}</version> |
| 196 |
<configuration> |
| 197 |
<complianceLevel>1.6</complianceLevel> |
| 198 |
<includes> |
| 199 |
<include>**/*.java</include> |
| 200 |
<include>**/*.aj</include> |
| 201 |
</includes> |
| 202 |
</configuration> |
| 203 |
<executions> |
| 204 |
<execution> |
| 205 |
<id>compile_with_aspectj</id> |
| 206 |
<goals> |
| 207 |
<goal>compile</goal> |
| 208 |
</goals> |
| 209 |
</execution> |
| 210 |
<execution> |
| 211 |
<id>test-compile_with_aspectj</id> |
| 212 |
<goals> |
| 213 |
<goal>test-compile</goal> |
| 214 |
</goals> |
| 215 |
</execution> |
| 216 |
</executions> |
| 217 |
<dependencies> |
| 218 |
<dependency> |
| 219 |
<groupId>org.aspectj</groupId> |
| 220 |
<artifactId>aspectjrt</artifactId> |
| 221 |
<version>${aspectj.runtime.version}</version> |
| 222 |
</dependency> |
| 223 |
<dependency> |
| 224 |
<groupId>org.aspectj</groupId> |
| 225 |
<artifactId>aspectjtools</artifactId> |
| 226 |
<version>${aspectj.runtime.version}</version> |
| 227 |
</dependency> |
| 228 |
</dependencies> |
| 229 |
</plugin> |
| 230 |
|
| 231 |
... |
| 232 |
+------------------------------------------ |
| 233 |
|
| 234 |
Besides including the correct parent POM and the required dependencies from aspectjrt and |
| 235 |
the validation-api project, the POM of the validation-aspect project must also define the |
| 236 |
full aspectj-maven-plugin configuration to perform the aspectj compilation. |
| 237 |
|
| 238 |
Note that aspectjrt and aspectjtools should be included as dependencies for the aspectj-maven-plugin |
| 239 |
as illustrated here to ensure that the same versions of AspectJ used for the AspectJ compilation |
| 240 |
are used throughout the reactor. |
| 241 |
|
| 242 |
The implementation of the Aspect itself can appear somewhat complex, despite only being a single |
| 243 |
active method. The main relevant method call is <<<validatable.validateInternalState();>>> which appears |
| 244 |
towards the end of the <<<performValidationAfterCompoundConstructor>>> method. This is the place where |
| 245 |
this Aspect invokes the method from the validation-api, and therefore lets the object validate its internal state. |
| 246 |
The other two methods in the aspect are placeholders for two Pointcut expressions defining exactly when |
| 247 |
the advice should be called. In this example case, we want to invoke validation after any constructor other |
| 248 |
than a default constructor is called. |
| 249 |
|
| 250 |
------------------------------------------ |
| 251 |
Why would you not want to perform validation after a default constructor is called? |
| 252 |
Consider the lifecycle for frameworks which create an object instance by calling the |
| 253 |
default constructor of a class, followed by poulating its internal state |
| 254 |
(i.e. its private members) using reflection. |
| 255 |
Some such frameworks include JAXB and JPA, implying that validation cannot be performed |
| 256 |
immediately after a default constructor has been run since the state of |
| 257 |
the object is still empty. |
| 258 |
------------------------------------------ |
| 259 |
|
| 260 |
The aspect is implemented as a standard Java Class using AspectJ annotations, as shown below: |
| 261 |
|
| 262 |
+------------------------------------------ |
| 263 |
/** |
| 264 |
* The aspect enforcing validity on a class implementing Validatable (i.e. Entities). |
| 265 |
* This aspect should be fired immediately after a non-default constructor is invoked, |
| 266 |
* and is intended to run as a singleton. |
| 267 |
* |
| 268 |
* Validation should be run only once, and only after the constructor of the ultimate |
| 269 |
* created instance is run (default AspectJ behaviour is to run the Aspect after any |
| 270 |
* constructor within the inheritance hierarchy is executed [i.e. after constructors |
| 271 |
* in superclasses are run, within the constructor of subtypes]). |
| 272 |
*/ |
| 273 |
@Aspect |
| 274 |
public class ValidationAspect { |
| 275 |
|
| 276 |
// Our log |
| 277 |
private static final Logger log = LoggerFactory.getLogger(ValidationAspect.class); |
| 278 |
|
| 279 |
/** |
| 280 |
* Pointcut defining a default constructor within any class. |
| 281 |
*/ |
| 282 |
@Pointcut("initialization(*.new())") |
| 283 |
void anyDefaultConstructor() { |
| 284 |
} |
| 285 |
|
| 286 |
/** |
| 287 |
* Defines a Pointcut for any constructor in a class implementing Validatable - |
| 288 |
* except default constructors (i.e. those having no arguments). |
| 289 |
* |
| 290 |
* @param joinPoint The currently executing joinPoint. |
| 291 |
* @param aValidatable The Validatable instance just created. |
| 292 |
*/ |
| 293 |
@Pointcut(value = "initialization(se.jguru.nazgul.tools.validation.api.Validatable+.new(..)) " |
| 294 |
+ "&& this(aValidatable) " |
| 295 |
+ "&& !anyDefaultConstructor()", argNames = "joinPoint, aValidatable") |
| 296 |
void anyNonDefaultConstructor(final JoinPoint joinPoint, final Validatable aValidatable) { |
| 297 |
} |
| 298 |
|
| 299 |
/** |
| 300 |
* Validation aspect, performing its job after calling any constructor except |
| 301 |
* non-private default ones (having no arguments). |
| 302 |
* |
| 303 |
* @param joinPoint The currently executing joinPoint. |
| 304 |
* @param validatable The validatable instance just created. |
| 305 |
* @throws InternalStateValidationException |
| 306 |
* if the validation of the validatable failed. |
| 307 |
*/ |
| 308 |
@AfterReturning(value = "anyNonDefaultConstructor(joinPoint, validatable)", argNames = "joinPoint, validatable") |
| 309 |
public void performValidationAfterCompoundConstructor(final JoinPoint joinPoint, final Validatable validatable) |
| 310 |
throws InternalStateValidationException { |
| 311 |
|
| 312 |
if (log.isDebugEnabled()) { |
| 313 |
log.debug("Validating instance of type [" + validatable.getClass().getName() + "]"); |
| 314 |
} |
| 315 |
|
| 316 |
if (joinPoint.getStaticPart() == null) { |
| 317 |
log.warn("Static part of join point was null for validatable of type: " |
| 318 |
+ validatable.getClass().getName(), new IllegalStateException()); |
| 319 |
return; |
| 320 |
} |
| 321 |
|
| 322 |
// Ignore calling validateInternalState when we execute constructors in |
| 323 |
// any class but the concrete Validatable class. |
| 324 |
final ConstructorSignature sig = (ConstructorSignature) joinPoint.getSignature(); |
| 325 |
final Class<?> constructorDefinitionClass = sig.getConstructor().getDeclaringClass(); |
| 326 |
if (validatable.getClass() == constructorDefinitionClass) { |
| 327 |
|
| 328 |
// Now fire the validateInternalState method. |
| 329 |
validatable.validateInternalState(); |
| 330 |
|
| 331 |
} else { |
| 332 |
|
| 333 |
log.debug("Ignored firing validatable for constructor defined in [" |
| 334 |
+ constructorDefinitionClass.getName() + "] and Validatable of type [" |
| 335 |
+ validatable.getClass().getName() + "]"); |
| 336 |
} |
| 337 |
} |
| 338 |
} |
| 339 |
+------------------------------------------ |
| 340 |
|
| 341 |
* 4. Include Aspects into aspectParentPOM |
| 342 |
|
| 343 |
The last piece of the AspectJ plugin puzzle is the inclusion of our validation-aspect into the |
| 344 |
standard build cycle, which is performed within the aspectParentPOM project. The aspectParentPOM |
| 345 |
must therefore include a dependency on the <<<validation-aspect>>> project, and use the rootParentPOM |
| 346 |
for parent. |
| 347 |
|
| 348 |
+------------------------------------------ |
| 349 |
<!-- +========================================= --> |
| 350 |
<!-- | Define the Parent POM --> |
| 351 |
<!-- +========================================= --> |
| 352 |
<parent> |
| 353 |
<groupId>some.group.id</groupId> |
| 354 |
<artifactId>rootParentPOM</artifactId> |
| 355 |
<version>1.0.0-SNAPSHOT</version> |
| 356 |
</parent> |
| 357 |
|
| 358 |
<!-- +========================================= --> |
| 359 |
<!-- | Dependency (management) settings --> |
| 360 |
<!-- +========================================= --> |
| 361 |
<dependencyManagement> |
| 362 |
<dependencies> |
| 363 |
<dependency> |
| 364 |
<groupId>some.group.id</groupId> |
| 365 |
<artifactId>validation-aspect</artifactId> |
| 366 |
<version>1.0.0-SNAPSHOT</version> |
| 367 |
</dependency> |
| 368 |
</dependencies> |
| 369 |
</dependencyManagement> |
| 370 |
<dependencies> |
| 371 |
<!-- Include AOP dependencies --> |
| 372 |
<dependency> |
| 373 |
<groupId>some.group.id</groupId> |
| 374 |
<artifactId>validation-aspect</artifactId> |
| 375 |
</dependency> |
| 376 |
<dependency> |
| 377 |
<groupId>org.aspectj</groupId> |
| 378 |
<artifactId>aspectjrt</artifactId> |
| 379 |
</dependency> |
| 380 |
|
| 381 |
... |
| 382 |
</dependencies> |
| 383 |
|
| 384 |
<!-- +========================================= --> |
| 385 |
<!-- | Build settings --> |
| 386 |
<!-- +========================================= --> |
| 387 |
<build> |
| 388 |
<plugins> |
| 389 |
<plugin> |
| 390 |
<groupId>org.codehaus.mojo</groupId> |
| 391 |
<artifactId>aspectj-maven-plugin</artifactId> |
| 392 |
<version>${project.version}</version> |
| 393 |
<configuration> |
| 394 |
<complianceLevel>1.6</complianceLevel> |
| 395 |
<includes> |
| 396 |
<include>**/*.java</include> |
| 397 |
<include>**/*.aj</include> |
| 398 |
</includes> |
| 399 |
<aspectDirectory>src/main/aspect</aspectDirectory> |
| 400 |
<testAspectDirectory>src/test/aspect</testAspectDirectory> |
| 401 |
<XaddSerialVersionUID>true</XaddSerialVersionUID> |
| 402 |
<showWeaveInfo>true</showWeaveInfo> |
| 403 |
<aspectLibraries> |
| 404 |
<aspectLibrary> |
| 405 |
<groupId>some.group.id</groupId> |
| 406 |
<artifactId>validation-aspect</artifactId> |
| 407 |
</aspectLibrary> |
| 408 |
</aspectLibraries> |
| 409 |
</configuration> |
| 410 |
<executions> |
| 411 |
<execution> |
| 412 |
<id>compile_with_aspectj</id> |
| 413 |
<goals> |
| 414 |
<goal>compile</goal> |
| 415 |
</goals> |
| 416 |
</execution> |
| 417 |
<execution> |
| 418 |
<id>test-compile_with_aspectj</id> |
| 419 |
<goals> |
| 420 |
<goal>test-compile</goal> |
| 421 |
</goals> |
| 422 |
</execution> |
| 423 |
</executions> |
| 424 |
<dependencies> |
| 425 |
<dependency> |
| 426 |
<groupId>org.aspectj</groupId> |
| 427 |
<artifactId>aspectjtools</artifactId> |
| 428 |
<version>${aspectj.runtime.version}</version> |
| 429 |
</dependency> |
| 430 |
<dependency> |
| 431 |
<groupId>some.group.id</groupId> |
| 432 |
<artifactId>validation-aspect</artifactId> |
| 433 |
<version>1.0.0-SNAPSHOT</version> |
| 434 |
</dependency> |
| 435 |
</dependencies> |
| 436 |
</plugin> |
| 437 |
</plugins> |
| 438 |
</build> |
| 439 |
+------------------------------------------ |
| 440 |
|
| 441 |
For all project now using the <<<aspectParentPOM>>> as their parent, the validationAspect will |
| 442 |
be woven into all classes implementing the Validatable interface. This means you can perform |
| 443 |
automatic AspectJ-driven validation in objects inside or outside of any container. |