Java Reference
In-Depth Information
Then you have an implementation for each interface with println statements to let you know when
the methods are executed.
package com.apress.springenterpriserecipes.calculator;
public class MaxCalculatorImpl implements MaxCalculator {
public double max(double a, double b) {
double result = (a >= b) ? a : b;
System.out.println("max(" + a + ", " + b + ") = " + result);
return result;
package com.apress.springenterpriserecipes.calculator;
public class MinCalculatorImpl implements MinCalculator {
public double min(double a, double b) {
double result = (a <= b) ? a : b;
System.out.println("min(" + a + ", " + b + ") = " + result);
return result;
Now suppose you also want ArithmeticCalculatorImpl to perform the max() and min() calculation.
As the Java language supports single inheritance only, it is not possible for the ArithmeticCalculatorImpl
class to extend both the MaxCalculatorImpl and MinCalculatorImpl classes at the same time. The only
possible way is to extend either class (e.g., MaxCalculatorImpl ) and implement another interface (e.g.,
MinCalculator ), either by copying the implementation code or delegating the handling to the actual
implementation class. In either case, you have to repeat the method declarations.
With introduction, you can make ArithmeticCalculatorImpl dynamically implement both the
MaxCalculator and MinCalculator interfaces by using the implementation classes MaxCalculatorImpl
and MinCalculatorImpl . It has the same effect as multiple inheritance from MaxCalculatorImpl and
MinCalculatorImpl . The brilliant idea behind introduction is that you needn't modify the
ArithmeticCalculatorImpl class to introduce new methods. That means you can introduce methods
to your existing classes even without source code available.
Tip You may wonder how an introduction can do that in Spring AOP. The answer is a dynamic proxy . As
you may recall, you can specify a group of interfaces for a dynamic proxy to implement. Introduction works by
adding an interface (e.g., MaxCalculator ) to the dynamic proxy. When the methods declared in this interface
are called on the proxy object, the proxy will delegate the calls to the back-end implementation class (e.g.,
MaxCalculatorImpl ).
Introductions, like advices, must be declared within an aspect. You may create a new aspect or reuse
an existing aspect for this purpose. In this aspect, you can declare an introduction by annotating an
arbitrary field with the @DeclareParents annotation.
Search WWH ::

Custom Search