Spring 3.0 tutorial – part 5 (Setter DI with Spring AOP and AspectJ)

This is a very simple Spring AOP tutorial using AspectJ. This assumes that you have gone through the “Setting up Java, Maven and Eclipse” tutorial and the other Spring tutorials 1 to 3. This annotation profiles the time taken to execute the annotated methods.

You need to have a project structure as shown below with the relevant artifacts.

spring-aop-tut-1

Step 1: pom.xml file with spring dependendencies. You can try using different (i.e. latest version of spring).

Spring Architecture

Spring Architecture

Step 2: Define an annotation. The methods that are annotated with this annotation “@Profile ” will be profiled.

Step 3: Define the Aspect “ProfileAspect“, which actually performs the profiling on methods that are annotated with “@Aspect“.

Step 4: Define the DAO layer Java interface and implementation for Course.

Spring annotations for DI

Spring annotations for DI

Step 3: Define the Service layer Java interface and implementation for Course.

Note: Note that “CoursDaoImpl” need to be injected via Spring into the “CourseServiceImpl”. The @Profile annotation is added to gather times.

Step 4: The Spring context XML file that wires up dependnecies. It defines the DAO and Service Java classes with “CoursDaoImpl” being injected into “CourseServiceImpl” via the setter injection using annotations.

conf/courseApplicationContext.xml

Note: “aop:aspectj-autoproxy” is added.

Step 5: Finally, bootstrap the “courseApplicationContext.xml” via the App.java with the main method to execute this stand alone.

Output:

Note: You can see the “52392” ns and “1020110” ns for the execution of methods “readAllCourses” and “findAllCourses” respectively. AOP is very powerful for things like

1) Logging/Auditing.
2) Profiling time/memory.
3) Service retry.

These are all cross-cutting concerns.


Java developer & architect Q&As

Java developers Q&As

Top