Java Reference
In-Depth Information
Logging is not the concern of BookServiceImpl . For logging, create an aspect as illustrated in
Listing 5-20 that will be woven into the BookService object, providing the logging wherever needed.
Listing 5-20. Aspect for Logging
1. package com.apress.aop;
2.
3. public class LoggingAspect {
4. public void logBefore() {
5.
6. System.out.println("Before calling getAllBooks");
7. }
8.
9. public void logAfter() {
10. System.out.println("After calling getAllBooks");
11. }
12. }
13.
Line 3 : LoggingAspect is a simple class with two methods.
Line 4 : The logBefore() method that should be invoked before getAllBooks()
is called.
Line 9 : the logAfter() method that should be invoked after the getAllBooks()
is called.
The LoggingAspect does its job without the BookServiceImpl asking it to do so. Furthermore,
because the BookServiceImpl does not need to know about the LoggingAspect , you are not
required to inject the LoggingAspect into the BookServiceImpl . This removes the unneeded
complexity from the BookServiceImpl code of having to inject LoggingAspect and having to check
whether LoggingAspect is null. As you may have noticed, LoggingAspect is a POJO. It becomes
an aspect when it is declared as an aspect in the Spring context. LoggingAspect can be applied
to the BookServiceImpl without the BookServiceImpl needing to explicitly call on it. In fact,
BookServiceImpl remains totally unaware of LoggingAspect 's existence. To make LoggingAspect
work as an aspect, all you need to do is declare it as one in the Spring configuration file.
Listing 5-21 illustrates the application context XML file that declares LoggingAspect as an aspect.
Listing 5-21. Configuration File
1. <?xml version="1.0" encoding="UTF-8"?>
2. <beans xmlns=" http://www.springframework.org/schema/beans "
3. xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance " xmlns:context=
" http://www.springframework.org/schema/context "
4. xmlns:aop=" http://www.springframework.org/schema/aop "
5. xsi:schemaLocation=" http://www.springframework.org/schema/beans
6. http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
7. http://www.springframework.org/schema/context
8. http://www.springframework.org/schema/context/spring-context-3.2.xsd
9. http://www.springframework.org/schema/aop
10. http://www.springframework.org/schema/aop/spring-aop-3.2.xsd " >
11.
 
Search WWH ::




Custom Search