img
Figure 7-2. Interface structure for introductions
As you can see, the MethodInterceptor interface defines an invoke() method. Using this method, you
provide the implementation for the interfaces that you are introducing and perform interception for any
additional methods as required. Implementing all methods for an interface inside a single method can
prove troublesome, and it is likely to result in an awful lot of code that you will have to wade through just
to decide which method to invoke. Thankfully, Spring provides a default implementation of
IntroductionInterceptor, DelegatingIntroductionInterceptor, which makes creating introductions
much simpler. To build an introduction using DelegatingIntroductionInterceptor, you create a class that
both inherits from DelegatingIntroductionInterceptor and implements the interfaces you want to
introduce. The DelegatingIntroductionInterceptor then simply delegates all calls to introduced methods
to the corresponding method on itself. Don't worry if this seems a little unclear; you will see an example of
it in the next section.
Just as you need to use a PointcutAdvisor when you are working with pointcut advice, you need
to use an IntroductionAdvisor to add introductions to a proxy. The default implementation of
IntroductionAdvisor is DefaultIntroductionAdvisor, which should suffice for most, if not all, of your
introduction needs. You should be aware that adding an introduction using ProxyFactory.addAdvice()
is not permitted and results in an AopConfigException being thrown. Instead, you should use the
addAdvisor() method and pass in an instance of the IntroductionAdvisor interface.
When using standard advice--that is, not introductions--it is possible for the same advice instance
to be used for many different objects. The Spring documentation refers to this as the per-class life cycle,
although you can use a single advice instance for many different classes. For introductions, the
introduction advice forms part of the state of the advised object, and as a result, you must have a distinct
advice instance for every advised object. This is called the per-instance life cycle. Because you must
ensure that each advised object has a distinct instance of the introduction, it is often preferable to create
a subclass of DefaultIntroductionAdvisor that is responsible for creating the introduction advice. This
way, you only need to ensure that a new instance of your advisor class is created for each object, because
it will automatically create a new instance of the introduction.
For example, we want to apply a before advice to the setFirstName() method on all instances of the
Contact class. Figure 7-3 shows the same advice that applies to all objects of the Contact type.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home