Java Reference
In-Depth Information
package com.apress.springenterpriserecipes.calculator;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.DeclareParents;
@Aspect
public class CalculatorIntroduction {
@DeclareParents(
value = " com.apress.springenterpriserecipes.calculator.
ArithmeticCalculatorImpl",
defaultImpl = MaxCalculatorImpl.class)
public MaxCalculator maxCalculator;
@DeclareParents(
value = " com.apress.springenterpriserecipes.calculator.
ArithmeticCalculatorImpl",
defaultImpl = MinCalculatorImpl.class)
public MinCalculator minCalculator;
}
The value attribute of the @DeclareParents annotation type indicates which classes are the targets
for this introduction. The interface to introduce is determined by the type of the annotated field. Finally,
the implementation class used for this new interface is specified in the defaultImpl attribute.
Through these two introductions, you can dynamically introduce a couple of interfaces to the
ArithmeticCalculatorImpl class. Actually, you can specify an AspectJ type-matching expression in
the value attribute of the @DeclareParents annotation to introduce an interface to multiple classes. For
the last step, don't forget to declare an instance of this aspect in the application context.
<beans ...>
...
<bean class="com.apress.springenterpriserecipes.calculator.
CalculatorIntroduction" />
</beans>
Because you have introduced both the MaxCalculator and MinCalculator interfaces to your
arithmetic calculator, you can cast it to the corresponding interface to perform the max() and min()
calculations.
package com.apress.springenterpriserecipes.calculator;
public class Main {
public static void main(String[] args) {
...
ArithmeticCalculator arithmeticCalculator =
(ArithmeticCalculator) context.getBean("arithmeticCalculator");
...
MaxCalculator maxCalculator = (MaxCalculator) arithmeticCalculator;
maxCalculator.max(1, 2);
Search WWH ::




Custom Search