View RSS Feed

Spring Framework

Introducing Behaviors to Your Spring Beans

Rate this Entry
by , 11-27-2011 at 10:55 PM (2596 Views)
In Spring AOP, you can use what is called an introduction (a special type of advice) that enables your objects to implement an interface dynamically, by providing the implementation class for that interface. This behavior can be multiplied to give the impression of multiple inheritance to your beans. To define an introduction, use the @DeclareParents annotation, which gives matching types a new parent.

Java Code:
package com.acme.springexamples.derivautos;
import org.aspectj.lang.annotation.Aspect; 
import org.aspectj.lang.annotation.DeclareParents;

public class AutoIntroducer {
	   value = "com.acme.springexample.Hybrid+", 
	   defaultImpl = Tesla.class)
	public static Auto auto;
To invoke an introduced interface just cast the appropriate interface on the matched parent type.
As you can see, AutoIntroducer is an aspect. It introduces the Auto interface onto Hybrid beans instead of using before, after, or around advice. Like <aop:declare-parents>, @DeclareParents annotation is made up of three parts:
The value attribute is equivalent to <aop:declare-parents>ís types-matching attribute. It identifies the kinds of beans that should be introduced with the interface.
The defaultImpl attribute is equivalent to <aop:declare-parents>ís default- impl attribute. It identifies the class that will provide the implementation for the introduction.
The static property that is annotated by @DeclareParents specifies the interface that is to be introduced.

As with any aspect, youíll need to declare AutoIntroducer as a bean in the Spring application context:

Java Code:
<bean class="com.acme.springexamples.derivautos.AutoIntroducer" />
By using the tag, <aop:aspectj-autoproxy> the beans annotated with @Aspect will be found and proxy created automatically that delegates calls to either the proxied bean or to the introduction implementation.

@DeclareParents has no equivalent to <aop:declare-parents>ís delegate-ref attribute because it is an @AspectJ annotation. Itís annotations arenít bean-aware. So if you want to delegate to a bean thatís configured with Spring, then you have to use <aop:declare-parents>.

Submit "Introducing Behaviors to Your Spring Beans" to Facebook Submit "Introducing Behaviors to Your Spring Beans" to Digg Submit "Introducing Behaviors to Your Spring Beans" to Submit "Introducing Behaviors to Your Spring Beans" to StumbleUpon Submit "Introducing Behaviors to Your Spring Beans" to Google

Bean , Spring 3