Você está na página 1de 28

Professional Open Source

Source™

Aspect-Oriented Middleware
Middleware Applications with Plain Old Java Objects

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 8/2/2005 1

Topics
Professional Open Source™

– What is AOM/AOP?
– JBoss AOP framework
– Prepackaged Middleware Aspects
• Dynamic Aspects
• Metadata Driven Aspects

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 2

1
What is AOP?
Professional Open Source™

– Modular way of defining and applying cross-cutting concerns


– Functionality that is not specific to any particular class
– Code that looks like it has structure, but cannot be described in OOP
– Modular way of layering code like an onion
– Turning any execution point in the Java runtime into an event
• Writing event handlers for these events
• Providing a “query” language to specify these points

Class1 Class1
CROSS HIERARCHY

Class2 Class3 Class4 Class2 Class3 Class4

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 3

What is AOM?
Professional Open Source™

Aspect Orientation addresses the notion of an assembly at or below the


component level
– Assembly exists at different levels in all software systems
1. Integration Level
2. Component Level
3. Class Level

1) Assembly at integration level is traditionally addressed by using protocols and


interfaces (MOM, ESB, JBI, etc.)

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 4

2
2. Component Level in AOM
Professional Open Source™

2)

Today component level is addressed by fixed container contracts


– EJB, servlet, etc. component models
– Provide a fixed set of services (remoteness, security, transactions)
– Assembly between container components (J2EE Assembler role definition)
– Fixed contract is ”one-size-for-all” model – evidence shows that there is no one
size that fits for all purposes

AOM formalizes the assembly of the container services


– Can be a predefined fixed contract, such as EJB container
– Can be customized for a plain old Java object (POJO) using advices developed
in-house or by 3rd party (will define what is an advice in following slides)
– Can be dynamic and changed based on run-time requirements
– This is ”custom-size-for-all” model -- allows you to implement a container
contract using a proven framework and known practices for your needs
– System level aspects

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 5

3. Class Level
Professional Open Source™

3)

Assemble class level functionality declaratively rather than statically at


compile time
– Inheritance or delegation are fixed at compile time
– Aspect assembly can be declared and modified without compilation
– Track class field usage (design by contract), constructor usage (count or restrict
number of instances in the virtual machine), etc.
– Move repetitive code outside of the business code implementation (traditionally
done by inheritance or delegation but cannot be changed after compiled). For
example, tracing, metrics, etc.
– Application level aspects

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 6

3
Cross-cutting Concern
Professional Open Source™

public
publicclass
classBankAccount
BankAccount { {

public
publicvoid
voidwithdraw(double
withdraw(doubleamount)
amount) { { What’s
What’s wrong?
wrong?
long start = System.currentTimeMillis();
long start = System.currentTimeMillis(); •• Difficult
Difficult to
to enable/disable
enable/disable
try
try{ { •• Have
Have to modify all
to modify all methods
methods
Connection with
with the
the same
same functionality
functionality
Connectioncon con==datasource.getConnection();
datasource.getConnection();
con.execute…(“select •• Bloated
Bloated code
code
con.execute…(“select……blahblahblah”);
blah”);
this.balance -= amount;
this.balance -= amount;
con.commit();
con.commit();
}}
finally
finally { {
long
longtotalTime
totalTime==System.currentTimeMillis()
System.currentTimeMillis()- -start;
start;
System.out.println(“withdraw
System.out.println(“withdrawtook
took““++totalTime);
totalTime);
}}
}}
}}

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 7

Where Does AOP Come In?


Professional Open Source™

– Can encapsulate “cross-cutting” functionality in one isolated place


• Similar to encapsulating functionality to Java classes and methods
– Execution points are declarative with “pointcuts”
• AOP pointcut language applies the encapsulated logic into Java
execution flow
– Encapsulated functionality can easily be removed from your application
code (change the declaration, rather than recompile code)

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 8

4
Terminology
Professional Open Source™

Advice
– Encapsulates cross-cutting code
– An “event handler” for an execution point in code
– Behavior you want to weave into your Java classes (metrics code)
Aspect
– Java class that defines advices
Pointcut
– AOP’s “query” language
– Declaratively selects any point within Java code
– For example, a method call, field access, instance construction
Invocation
– Object instance that represents an invocation and its context

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 9

Professional Open Source


Source™

Aspects and Advices in JBossAOP


Intercepting Java Calls

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 8/2/2005 10

5
Aspect and Advice
Professional Open Source™

Advice is the behavior you want to add


– This will be executed on a selected point in the code flow
Aspects encapsulate one or more advices
– Aspect itself is a regular Java class
– Contains one or more advice definitions
– Can use normal Java OOP features such as inheritance, delegation, methods
that are not used as advices
public
publicclass
class<classname>
<classname>extends
extendsX,
X,implements
implementsYY{{
public
publicObject Object<methodname>(org.jboss.aop.joinpoint.Invocation
<methodname>(org.jboss.aop.joinpoint.Invocationinv)
inv)throws
throwsThrowable
Throwable{{
try
try{{
////ininpath
path
… …
return
returninv.invokeNext();
inv.invokeNext(); ////proceed
proceedwith
withthe
theinvocation
invocation
}}
finally
finally {{
//out
//outpath path
......
}}

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 11

Aspects
Professional Open Source™

Sample metrics aspect with ‘profile’ advice


– Invocation instance holds the context of the invocation that was intercepted
(method arguments, metadata, etc.)

public
publicclass
classMetricsAspect
MetricsAspect{{

public
publicObject
Objectprofile(MethodInvocation
profile(MethodInvocationinvocation)
invocation)throws
throwsThrowable
Throwable{{ Advice
Advice
try
try{{
long
longstart
start==System.currentTimeMillis();
System.currentTimeMillis();
return
returninvocation.invokeNext();
invocation.invokeNext();
}}
finally
finally {{
long
longtotalTime
totalTime==System.currentTimeMillis()
System.currentTimeMillis()--start;
start;
System.out.println(invocation.getMethod()
System.out.println(invocation.getMethod()++““took
took““++totalTime)
totalTime)
}}
}}
}}

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 12

6
Aspects
Professional Open Source™

– invokeNext proceeds to the next advice or continues the original


invocation normally

public
publicclass
classMetricsAspect
MetricsAspect{ {

public
publicObject
Objectprofile(MethodInvocation
profile(MethodInvocationinvocation)
invocation)throws
throwsThrowable
Throwable{ { Advice
Advice
long start = System.currentTimeMillis();
long start = System.currentTimeMillis();
try
try{ {
return
returninvocation.invokeNext();
invocation.invokeNext();
}}
finally
finally { {
long
longtotalTime
totalTime==System.currentTimeMillis()
System.currentTimeMillis()- -start;
start;
System.out.println(invocation.getMethod()
System.out.println(invocation.getMethod()++““took took““++totalTime)
totalTime)
}}
}}
}}

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 13

Aspect Scope
Professional Open Source™

Aspects can be scoped depending on their usage


– Scope determines the number if aspect instances created in the VM

PER_VM
– Only one instance is created in the VM
– All threads execute on the same aspect instance
PER_CLASS
– One instance per adviced class is created.
– All threads executing on any instance of adviced class use the same aspect
instance
PER_INSTANCE
– One instance for every instanced object of an adviced class
– Threads that execute on the same object instance use the same aspect instance
PER_JOINPOINT
– One instance on every matched join point for every instance of adviced class
– Threads that execute on the same field, method or constructor of an object
instance share the same aspect instance

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 14

7
Aspect Configuration
Professional Open Source™

Deployment descriptor META-INF/jboss-aop.xml


– Declare the name of your aspect class
– Declare where the advices should be applied (we will see this later)

jboss-aop.xml
<aop>
<aop>
<aspect
<aspectclass=“org.jboss.MetricsAspect”/>
class=“org.jboss.MetricsAspect”/>

<!–
<!–pointcut
pointcutdeclarations
declarations(will
(willsee
seelater)
later)-->
-->
......
</aop>
</aop>

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 15

Aspect Initialization
Professional Open Source™

Aspect can be initialized with standard setter injection


– Include JavaBean style method accessors in the aspect implementation
– Configure the initialization values in the deployment descriptor

jboss-aop.xml
<aop>
<aop>
<aspect
<aspectclass=“org.jboss.MetricsAspect”>
class=“org.jboss.MetricsAspect”>
<attribute
<attributename
name==”LogFile”>PerformanceMetrics.log</attribute>
”LogFile”>PerformanceMetrics.log</attribute>
</aspect>
</aspect>
......
</aop>
</aop>

– Assumes method setLogFile() is exposed in aspect implementation.


– Automatic type conversions exists for primitive types, Strings, URL, File,
InetAddress, org.w3c.dom.Document (arbitrary complex initialization structure as
DOM document), etc. (see the documentation for complete list).

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 16

8
Aspect Initialization
Professional Open Source™

If the aspect initialization depends on runtime properties or conditionals, you


can use an aspect factory implementation
– Implement org.jboss.aop.advice.AspectFactory interface
– Configure in the deployment descriptor

jboss-aop.xml
<aop>
<aop>
<aspect
<aspectname=“MetricsAspect”
name=“MetricsAspect”factory
factory==“org.acme.MetricsAspectFactory”/>
“org.acme.MetricsAspectFactory”/>
......
</aop>
</aop>

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 17

Professional Open Source


Source™

Pointcut Language
Declarative Selectors in JBossAOP

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 8/2/2005 18

9
Pointcuts and Bindings
Professional Open Source™

– Apply the aspect to your Java class


– Pointcut expression declares where the aspect is to be invoked

jboss-aop.xml
<aop>
<aop>
<aspect
<aspectclass=“org.jboss.MetricsAspect”/>
class=“org.jboss.MetricsAspect”/>

<bind
<bindpointcut=“execution(public
pointcut=“execution(publicvoid
voidBankAccount->credit(java.lang.String,
BankAccount->credit(java.lang.String,int))”>
int))”>
<advice
<adviceaspect=“org.jboss.MetricsAspect”
aspect=“org.jboss.MetricsAspect”name=“profile”/>
name=“profile”/>
</bind>
</bind>

</aop>
</aop>

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 19

Pointcuts and Bindings


Professional Open Source™

JBossAOP supports two kinds of pointcut wildcards


– ‘*’ matches zero or more characters
– ‘..’ matches any number of parameters on method or constructor call

<!--
<!-- Advice
Adviceall
alltoString()
toString()methods
methodsininorg.jboss
org.jbosspackage
package-->-->
<bind
<bindpointcut
pointcut==“execution(public
“execution(publicjava.lang.String
java.lang.Stringorg.jboss.*->toString())”>
org.jboss.*->toString())”>
<advice
<adviceaspect
aspect==”com.acme.MyAspect”
”com.acme.MyAspect”name name==”formatStrings”/>
”formatStrings”/>
</bind>
</bind>

<!–
<!–Advice
Adviceall
alldeploy()
deploy()methods
methodsininMainDeployer
MainDeployerclass
classregardless
regardlessof
ofparameter
parameterdeclarations
declarations-->
-->
<bind
<bindpointcut
pointcut==“execution(public
“execution(publicvoid
voidorg.jboss.deployment.MainDeployer->deploy(..))”
org.jboss.deployment.MainDeployer->deploy(..))”>>
<advice
<adviceaspect
aspect==“com.acme.MyAspect”
“com.acme.MyAspect”name
name==“authorizeDeploy”/>
“authorizeDeploy”/>
</bind>
</bind>

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 20

10
Pointcuts and Bindings
Professional Open Source™

Pointcut matching can be made based on declared exceptions and subclass


types as well
– Any declared exceptions in the advice declaration are matched to Java classes
– An $instanceof{} operator can be used to declare matching on subclasses

<!--
<!-- Advice
Adviceall
alltoString()
toString()methods
methodsininorg.jboss.ejb.Container
org.jboss.ejb.Containerand
andits
itssubclasses
subclasses-->
-->
<bind
<bindpointcut
pointcut==“execution(public
“execution(publicString
String $instanceof{org.jboss.ejb.Container}->toString())”>
$instanceof{org.jboss.ejb.Container}->toString())”>
<advice
<adviceaspect
aspect==”com.acme.MyAspect”
”com.acme.MyAspect”name name==”formatStrings”/>
”formatStrings”/>
</bind>
</bind>

<!–
<!–Advice
Adviceall
alldeploy()
deploy()methods
methodsininMainDeployer
MainDeployerclass
classthat
thatdeclare
declaregiven
givenexceptions
exceptions-->
-->
<bind
<bind pointcut = “execution(public void org.jboss.deployment.MainDeployer->deploy(..)throws
pointcut = “execution(public void org.jboss.deployment.MainDeployer->deploy(..) throws
org.jboss.deployment.DeploymentException,
org.jboss.deployment.DeploymentException,java.net.MalformedURLException)”>
java.net.MalformedURLException)”>
<advice
<adviceaspect
aspect==“com.acme.MyAspect”
“com.acme.MyAspect”namename==“authorizeDeploy”/>
“authorizeDeploy”/>
</bind>
</bind>

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 21

Pointcuts and Bindings


Professional Open Source™

– For method attributes, ‘!’ negator is accepted

<!--
<!-- Advice
Adviceall
allnon-static
non-staticmethods
methodsininorg.jboss.ejb.*
org.jboss.ejb.*package
package-->-->
<bind
<bindpointcut
pointcut==“execution(public
“execution(public!static
!static** org.jboss.ejb.*->*(..))”>
org.jboss.ejb.*->*(..))”>
<advice
<adviceaspect
aspect==”com.acme.MyAspect”
”com.acme.MyAspect”name name==”logCall”
”logCall”/>/>
</bind>
</bind>

– Constructors can be declared with ‘new’ keyword


– Constructors do not have a return type

<!--
<!-- Advice
Adviceall
allnon-public
non-publicConstructors
Constructorsininorg.jboss.ejb.Container
org.jboss.ejb.Containerclass
class-->
-->
<bind pointcut = “execution(!public org.jboss.ejb.Container->new(..))”>
<bind pointcut = “execution(!public org.jboss.ejb.Container->new(..))”>
<advice
<adviceaspect
aspect==”com.acme.MyAspect”
”com.acme.MyAspect”name name==”logCall”
”logCall”/>/>
</bind>
</bind>

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 22

11
Pointcuts and Bindings
Professional Open Source™

Advices can be added to either class methods or fields


– “execution” keyword is used for method pointcuts (notice that a constructor in
Java is just a special method)
– “field” keyword can be used for pointcutting an instance field (read or write)
– “get” keyword can be used for pointcutting a read of instance field value
– “set” keyword can be used for pointcutting a write of instance field value

<!--
<!-- Pointcut
Pointcuton
onaamethod
method-->
-->
<bind
<bindpointcut
pointcut==“execution(public
“execution(publicvoid
voidorg.jboss.deployment.MainDeployer->deploy(..))”>
org.jboss.deployment.MainDeployer->deploy(..))”>
<advice
<adviceaspect
aspect==”com.acme.MyAspect”
”com.acme.MyAspect”namename==”authorizeDeploy”/>
”authorizeDeploy”/>
</bind>
</bind>
<!–
<!–Pointcut
Pointcuton
oninstance
instancefield
fieldaccess
access-->
-->
<bind
<bindpointcut
pointcut==”field(public
”field(publicint
intcom.acme.PersonVO->SSN)”>
com.acme.PersonVO->SSN)”>
<advice
<adviceaspect
aspect==”com.acme.MyAspect”
”com.acme.MyAspect”namename==”invariant”/>
”invariant”/>
</bind>
</bind>
<!–
<!–Pointcut
Pointcuton
oninstance
instancefield
fieldwrite
writeaccess
access-->
-->
<bind
<bindpointcut
pointcut==”set(public
”set(publicint
intcom.acme.PersonVO->age)”>
com.acme.PersonVO->age)”>
<advice
<adviceaspect
aspect==”com.acme.MyAspect”
”com.acme.MyAspect”name name==”precondition”/>
”precondition”/>
</bind>
</bind>

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 23

Pointcuts and Bindings


Professional Open Source™

Additional keywords in the pointcut language


– “all” keyword is used to find all possible point cuts in a given expression
• Especially useful when used with annotations (will cover annotations in the
following slides)
– “call” keyword is similar to “execution” but adds caller side context information
• “within” and “withincode” keywords match any method and constructor calls
within the selected set
• E.g. execute advice if an instance of class Foo was invoked from an
instance of class Bar
– “has” and “hasfield” keywords can be used for additional conditions for setting up
join point selectors (whether a method, constructor or an instance field exists).

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 24

12
Pointcut Composition
Professional Open Source™

You can compose a pointcut from multiple pointcut expressions using


logical operators
– Logical not ’!’, logical and ’AND’ and logical or ’OR’ operators are accepted
– Parenthesis can be used to group expressions

<!--
<!-- Pointcut
Pointcuton
onaacall
callto
toMyClass
MyClassconstructor
constructorwhen
whencalled
calledwithin
withinthe
theFoo
Fooclass
class-->
-->
<bind pointcut = “within(org.wombat.Foo) AND call(public void org.acme.MyClass->new(..))”>
<bind pointcut = “within(org.wombat.Foo) AND call(public void org.acme.MyClass->new(..))”>
<advice
<adviceaspect
aspect==”com.acme.MyAspect”
”com.acme.MyAspect”name
name==”countMyClassOfFoo”/>
”countMyClassOfFoo”/>
</bind>
</bind>

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 25

Pointcut References
Professional Open Source™

With pointcut composition, expressions may get long and hard to read
– Repeating long expressions is not ideal
You can create named pointcut expressions and reference them in bindings
– <pointcut> tag
– Helps keeping the declarations more human-readable

<!–
<!–Select
Selectall
allpublic
publicmethods
methods-->
-->
<pointcut
<pointcutname
name==”public.methods”
”public.methods”
expr
expr ==”execution(public
”execution(public***->*(..))”/>
*->*(..))”/>

<!–
<!–Select
Selectall
allpublic
publicconstructors
constructors-->
-->
<pointcut name = ”public.constructors”
<pointcut name = ”public.constructors”
expr
expr ==”execution(public
”execution(public*->new(..))”/>
*->new(..))”/>

<!--
<!-- Trace
Traceall
allpublic
publicmethods
methodsand
andconstructors
constructors-->
-->
<bind
<bindpointcut
pointcut==“public.methods
“public.methodsOR
ORpublic.constructors”>
public.constructors”>
<advice
<adviceaspect
aspect==”com.acme.MyAspect”
”com.acme.MyAspect”name
name==”tracePublicMethodsAndConstructors”/>
”tracePublicMethodsAndConstructors”/>
</bind>
</bind>

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 26

13
Group Types with TypeDef
Professional Open Source™

For complex group of types or type conditions that resolve to a class, you
can create a new type group with <typedef>
– Useful especially when you have to repeat the group declaration a lot
– Instead of writing many pointcuts individually, create a new type definition
– Operators class(), has(), hasfield() and $instanceof{} are allowed in the typedef
clause
– You don’t have to rely as much on wildcard patterns that may have unexpected
consequences later as the software evolves
<!–
<!–Create
Createaanew
newtype
typedefinition
definitionout
outof
ofvalue
valueobject
objectclasses
classesinindifferent
differentpackages
packages-->
-->
<typedef name = ”ValueObjects”
<typedef name = ”ValueObjects”
expr
expr ==”$instanceof{org.acme.ValueObject}
”$instanceof{org.acme.ValueObject}OR OR$instanceof{org.wombat.ValueObject}
$instanceof{org.wombat.ValueObject}AND
AND......”/>
”/>

<!--
<!-- count
countcreation
creationof
ofvalue
valueobjects
objectsfrom
fromaagiven
givenset
setof
ofvalue
valueobject
objectclasses
classesand
andtheir
theirsubclasses
subclasses-->
-->
<bind
<bindpointcut
pointcut==“execution(public
“execution(public$typedef{ValueObjects}->new(..))”>
$typedef{ValueObjects}->new(..))”>
<advice
<adviceaspect
aspect==”com.acme.MyAspect”
”com.acme.MyAspect”name name==”countCreatedVOs”/>
”countCreatedVOs”/>
</bind>
</bind>

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 27

Stack Advices
Professional Open Source™

Several advices can be bound to a pointcut

<bind
<bindpointcut
pointcut==”all(com.acme.BusinessObject)”>
”all(com.acme.BusinessObject)”>
<advice
<adviceaspect
aspect==”com.acme.MyAspect”
”com.acme.MyAspect”name
name==”myAdvice”/>
”myAdvice”/>
<advice
<advice aspect = ”com.acme.OtherAspect”name
aspect = ”com.acme.OtherAspect” name==”someAdvice”/>
”someAdvice”/>
</bind>
</bind>

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 28

14
Stack Advices
Professional Open Source™

Create a named set of advices to apply on Java objects


– Foundation for interceptor based containers

<stack
<stackname
name==”MyContainer”>
”MyContainer”>
<advice
<advicename
name==”log”
”log” aspect
aspect==”com.acme.MethodLogAspect”/>
”com.acme.MethodLogAspect”/>
<advice
<advicename
name==”security”
”security”aspect
aspect==”com.acme.SecurityAspect”/>
”com.acme.SecurityAspect”/>
<advice
<advicename
name==”tx”
”tx”aspect
aspect==”com.acme.TransactionAspect”/>
”com.acme.TransactionAspect”/>
</stack>
</stack>

<bind
<bindpointcut
pointcut==”all(com.acme.BusinessObject)”>
”all(com.acme.BusinessObject)”>
<stack-ref
<stack-refname
name==”MyContainer”/>
”MyContainer”/>
</bind>
</bind>

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 29

Professional Open Source


Source™

Dynamic AOP

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 8/2/2005 30

15
Dynamic AOP
Professional Open Source™

Every AOPized class has an extended interface


– At classloading time, bytecode manipulation forces AOP POJOs to implement a
standard AOP interface.

public
publicinterface
interfaceInstanceAdvised
InstanceAdvised{{
public
publicInstanceAdvisor
InstanceAdvisor_getInstanceAdvisor();
_getInstanceAdvisor();
public
publicvoid
void_setInstanceAdvisor(InstanceAdvisor
_setInstanceAdvisor(InstanceAdvisornewAdvisor);
newAdvisor);
}}

public
publicinterface
interfaceAdvised
Advisedextends
extendsInstanceAdvised
InstanceAdvised{{
Advisor _getAdvisor();
Advisor _getAdvisor();
}}

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 31

Dynamic AOP
Professional Open Source™

– Dynamic insertion of interceptors per object instance


– Object instance can hold its own metadata

public
public interface
interface InstanceAdvisor
InstanceAdvisor
{{
public
public SimpleMetaData
SimpleMetaData getMetaData();
getMetaData();
public
public Interceptor[]
Interceptor[] getInterceptors();
getInterceptors();
public
public Interceptor[]
Interceptor[] getInterceptors(Interceptor[]
getInterceptors(Interceptor[] baseChain);
baseChain);
public
public boolean
boolean hasAspects();
hasAspects();

public
public void
void insertInterceptor(Interceptor
insertInterceptor(Interceptor interceptor);
interceptor);
public
public void
void removeInterceptor(String
removeInterceptor(String name);
name);
public
public void
void appendInterceptor(Interceptor
appendInterceptor(Interceptor interceptor);
interceptor);

public
public void
void insertInterceptorStack(String
insertInterceptorStack(String stackName);
stackName);
public
public void
void removeInterceptorStack(String
removeInterceptorStack(String name);
name);
public
public void
void appendInterceptorStack(String
appendInterceptorStack(String stackName);
stackName);
}}

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 32

16
Dynamic Pointcuts
Professional Open Source™

AdviceBinding
AdviceBinding binding
binding == new
new AdviceBinding("execution(POJO->new(..))",
AdviceBinding("execution(POJO->new(..))", null);
null);
binding.addInterceptor(SimpleInterceptor.class);
binding.addInterceptor(SimpleInterceptor.class);
AspectManager.instance().addBinding(binding);
AspectManager.instance().addBinding(binding);

jboss-aop.xml
<aop>
<aop>
<prepare
<prepareexpr="execution(POJO->new(..))"/>
expr="execution(POJO->new(..))"/>
</aop>
</aop>

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 33

Professional Open Source


Source™

Annotated Aspects

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 8/2/2005 34

17
Java Annotations
Professional Open Source™

JDK 1.5 adds a new language feature – annotations


– Formalizes the XDoclet approach of adding descriptive tags to your Java code

JBossAOP can be used with annotations instead of XML deployment


descriptors
– XML deployment descriptors are declarative, and can be changed without
recompilation
– Annotations are compiled, and changes require recompilation
– Some features are better expressed as Java language level attributes to
methods, fields and classes (for example, transactional attributes)
– Some features are better expressed as easily changeable, and dynamic,
configuration (tracing, metrics, authorization roles, etc.)

Annotations can also be used with JDK1.4 with JBossAOP annotation


precompiler.

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 35

Define Annotation
Professional Open Source™

Defining custom annotations is easy


– Similar to defining interfaces

public
public@interface
@interfaceReadLock
ReadLock{}{}
public
public@interface
@interfaceWriteLock
WriteLock{}{}

ReadLock and WriteLock are marker annotations


– No additional elements

class
classXX{ {
@ReadLock
@ReadLockpublic
publicObject
ObjectgetData()
getData() { {. .. .. .} }
@WriteLock
@WriteLockpublic
publicvoid
voidsetData(Object
setData(Objectdata) data){ {. .. .. .} }
}}

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 36

18
Define Annotation
Professional Open Source™

You can add elements to annotations


– Types can be primitives, strings, enums, classes or annotations

public
public @interface
@interface WriteLock
WriteLock {{
int
int timeout();
timeout();
}}

class
class XX {{
@WriteLock(timeout
@WriteLock(timeout == 5000)
5000)
public
public void
void setData(Object
setData(Object data)
data) {{ .. .. .. }}
}}

See JDK 1.5 documentation for full details.

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 37

Annotation Compiler for Java 1.4


Professional Open Source™

JBossAOP comes with a precompiler that you can use against Java 1.4
compliant codebase
– Annotation types are defined as interfaces
– Annotations are part of javadoc comments

package
package com.mypackage;
com.mypackage;

public
public interface
interface RWLock
RWLock {{
int
int timeout();
timeout();
}}

/**
/**
** @@com.mypackage.RWLock
@@com.mypackage.RWLock (timeout=3)
(timeout=3)
*/*/
public
public int
int myMethod()
myMethod() {{ …
… }}

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 38

19
Annotation Compiler for Java 1.4
Professional Open Source™

Notice some important differences:


– Starts with a double sign ’@@’
– Must have whitespace between annotation type name and element names
– Must use the fully qualified name of the annotation interface (cannot use
imports)
– No default values for elements (JDK 1.5 annotations support this feature)

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 39

JBossAOP Defined Annotations


Professional Open Source™

org.jboss.aop.Aspect
– Marks a class as an aspect
org.jboss.aop.PointcutDef
– Defines a named pointcut declaration
org.jboss.aop.Bind
– Binds an advice within aspect with a given pointcut

@Aspect
@Aspect (scope
(scope == Scope.PER_VM)
Scope.PER_VM)
public
public class
class MyAspect
MyAspect {{
@PointcutDef
@PointcutDef (”execution(\”public
(”execution(\”public ** com.acme.*->create(..)\”)
com.acme.*->create(..)\”)
public
public static
static Pointcut
Pointcut createMethods;
createMethods;

@Bind
@Bind (pointcut
(pointcut == ”createMethods”)
”createMethods”)
public
public Object
Object countInstances(Invocation
countInstances(Invocation invocation)
invocation) {{ …
… }}
}}

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 40

20
Annotations in Pointcuts
Professional Open Source™

You can take advantage of annotations in pointcut expressions as well


– At times better than using wildcards and fixed class and method names

all(@com.acme.createMethod)
– All methods marked with @createMethod annotation

withincode(@javax.ejb.Entity->new(..))
– Public constructors of EJB3 entity classes

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 41

Professional Open Source


Source™

Aspect Examples
POJO Middleware

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 8/2/2005 42

21
ReadWriteLock Aspect
Professional Open Source™

public
publicclass
classReadWriteLockAspect
ReadWriteLockAspect{{
java.util.concurrent.ReentrantReadWriteLock
java.util.concurrent.ReentrantReadWriteLocklock
lock==new
newReentrantReadWriteLock();
ReentrantReadWriteLock();

public ObjectreadLock(Invocation
publicObject readLock(Invocationinvocation)
invocation)throws
throwsThrowable
Throwable{{
try {
try {
lock.readLock().lock();
lock.readLock().lock();
return
returninvocation.invokeNext();
invocation.invokeNext();
}}
finally
finally {{
lock.readLock().unlock();
lock.readLock().unlock();
}}
}}
public
publicObject
ObjectwriteLock(Invocation
writeLock(Invocationinvocation)
invocation)throws
throwsThrowable
Throwable{{
try
try{{
lock.writeLock().lock();
lock.writeLock().lock();
return
returninvocation.invokeNext();
invocation.invokeNext();
}}
finally
finally {{
lock.writeLock().unlock();
lock.writeLock().unlock();
}}

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 43

ReadWriteLock Aspect
Professional Open Source™

– Specify pointcut that selects @ReadLock and @WriteLock annotations

<aop>
<aop>
<aspect
<aspectclass=“ReadWriteLockAspect”
class=“ReadWriteLockAspect”scope=“PER_INSTANCE”/>
scope=“PER_INSTANCE”/>

<bind
<bindpointcut=“execution(!static
pointcut=“execution(!static***->@org.jboss.ReadLock(..))”>
*->@org.jboss.ReadLock(..))”>
<advice
<adviceaspect=“ReadWriteLockAspect”
aspect=“ReadWriteLockAspect”name=“readLock”/>
name=“readLock”/>
</bind>
</bind>

<bind
<bindpointcut=“execution(!static
pointcut=“execution(!static***->@org.jboss.WriteLock(..))”>
*->@org.jboss.WriteLock(..))”>
<advice
<adviceaspect=“ReadWriteLockAspect”
aspect=“ReadWriteLockAspect”name=“writeLock”/>
name=“writeLock”/>
</bind>
</bind>

</aop>
</aop>

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 44

22
Asynchronous Invocations
Professional Open Source™

Asynchronous Aspect
– Tag Methods
– Invoke them in background
– Obtain response asynchronously
– In-VM only
– Working on Remote asynchronous invocations

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 45

Asynchronous Invocations
Professional Open Source™

import
importorg.jboss.aspects.asynchronous.aspects.jboss.Asynchronous;
org.jboss.aspects.asynchronous.aspects.jboss.Asynchronous;

public
publicclass
classPOJO
POJO{{

public
publicvoid
voidprocessBusinessModel(){...}
processBusinessModel(){...}

@Asynchronous
@Asynchronous
public
publiclong
longprocessBusinessModel(...){}
processBusinessModel(...){}
}}

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 46

23
Asynchronous Invocations
Professional Open Source™

POJO
POJOpojo pojo==new
newPOJO(...);
POJO(...);
long
longresult result==pojo.processBusinessModel(...);
pojo.processBusinessModel(...); ////non-blocking
non-blockingcallcall
AsynchronousFacade
AsynchronousFacadefaçade façade==(AsynchronousFacade)pojo;
(AsynchronousFacade)pojo;
......
////do dosomesomeworkwork
......
ifif(facade.isDone())
(facade.isDone()){{
ifif(facade.getResponseCode()
(facade.getResponseCode()== ==OK)
OK) ////Test
Testresponse
responsecode
codereturned
returned
result
result==((Long)facade.getReturnValue()).longValue();
((Long)facade.getReturnValue()).longValue(); ////get
getmethod
methodresponse
response
else
elseifif(facade.getResponseCode()==TIMEOUT)
(facade.getResponseCode()==TIMEOUT){...} {...} ////Test
Testififmethod
methodtimed
timedout
out
else
else{{
AsynchronousResponse
AsynchronousResponseresponse response==facade.waitForResponse();
facade.waitForResponse(); ////blocking
blockingcall
call
IfIf(response.getResponseCode()==OK)
(response.getResponseCode()==OK) //// getmethod
get methodresponse
response
result=((Long)response.getReturnValue()).longValue();
result=((Long)response.getReturnValue()).longValue();
else
elseifif(response.getReponseCode()==TIMEOUT)
(response.getReponseCode()==TIMEOUT){...} {...} ////Test
Testififmethod
methodtimed
timedout
out
}}
}}

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 47

Transaction Demarcation
Professional Open Source™

Transaction demarcation (method, field, constructor)


– You can specify transaction boundaries within code
Tags can transparently interact with Transaction Manager
– Begin, suspend, commit and rollback transactions
– On method, field, or constructor execution
EJB adjectives used to specify transactional behavior
– Required, RequiresNew, Supports, Never, NotSupported, Mandatory
Complete control over when a rollback is triggered
– i.e. which thrown exceptions cause a rollback

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 48

24
Transaction Demarcation
Professional Open Source™

– Annotations or XML metadata can specify annotation

@Tx(TxType.REQUIRED)
@Tx(TxType.REQUIRED)
public
public void
void somepojoMethod()
somepojoMethod() {{ …
… }}

<metadata
<metadata tag="transaction"
tag="transaction" class="org.jboss.test.POJO">
class="org.jboss.test.POJO">
<method
<method name="somepojoMethod“>
name="somepojoMethod“>
<value>RequiresNew</value>
<value>RequiresNew</value>
</method>
</method>
</metadata>
</metadata>

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 49

Transactional Locking
Professional Open Source™

Enhanced Java “synchronized”


– Allows you to lock object/class for duration of a transaction
Can specify on any member field or method
– Locks object instance
Can specify for any constructor or static method, field
– Locks class access

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 50

25
Transactional Locking
Professional Open Source™

– Annotations or XML metadata can specify annotation

@TxSynchronized
@TxSynchronized
public
public void
void somepojoMethod()
somepojoMethod() {{ …
… }}

<metadata
<metadata tag="transactionSynchronized"
tag="transactionSynchronized" class="org.jboss.test.POJO">
class="org.jboss.test.POJO">
<method
<method name="somepojoMethod“/>
name="somepojoMethod“/>
</metadata>
</metadata>

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 51

Roled-based Security
Professional Open Source™

Secured access to any method, field, or constructor


– Only users of a certain role allowed to access
Authentication/Authorization integrated with JBoss Security
– Various Security Domains (LDAP, RDBMS, SRP, etc…)
Access to username available within other interceptors

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 52

26
Role-Based security
Professional Open Source™

XML metadata can specify annotation


<metadata
<metadatatag="security"
tag="security"class="org.jboss.test.aop.bean.SecuredPOJO">
class="org.jboss.test.aop.bean.SecuredPOJO">
<security-domain>other</security-domain>
<security-domain>other</security-domain>
<method-permission>
<method-permission>
<role-name>allowed</role-name>
<role-name>allowed</role-name>
<method><method-name>someMethod</method-name></method>
<method><method-name>someMethod</method-name></method>
</method-permission>
</method-permission>
<constructor-permission>
<constructor-permission>
<unchecked/>
<unchecked/>
<constructor><constructor-params/></constructor>
<constructor><constructor-params/></constructor>
</constructor-permission>
</constructor-permission>

<exclude-list>
<exclude-list>
<description>Methods
<description>Methodsthat
thatconnect
connectbe
beused</description>
used</description>
<method>
<method>
<method-name>excluded</method-name>
<method-name>excluded</method-name>
</method>
</method>
</exclude-list>
</exclude-list>
</metadata>
</metadata>

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 53

Role-Based security
Professional Open Source™

JDK 5.0 Annotations are usable


@SecurityDomain(“other”)
@SecurityDomain(“other”)
public
publicclass
classPOJO
POJO{ {

@Unchecked
@Uncheckedpublic
publicPOJO()
POJO(){}{}

@Exclude
@Excludepublic
publicexcludedMethod()
excludedMethod(){…}
{…}

@Permissions({“admin”,
@Permissions({“admin”,“manager”})
“manager”})
public
publicvoid
voidsomeMethod()
someMethod(){…}
{…}

@Permissions({“user”})
@Permissions({“user”})
public
publicstatic
staticint
intstatus;
status;

}}

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 54

27
Role-based Security
Professional Open Source™

Security information is available within advice/interceptors


– Useful if you want to do your own rule-based security

import
importjava.security.Principal;
java.security.Principal;

public
publicObject
Objectinvoke(org.jboss.aop.joinpoint.Invocation
invoke(org.jboss.aop.joinpoint.Invocationinvocation)
invocation)throws
throwsThrowable
Throwable
{{
Principal
Principalprincipal
principal==(Principal)invocation.getMetaData("security",
(Principal)invocation.getMetaData("security","principal");
"principal");
……
}}

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 55

Conclusion
Professional Open Source™

AOP Framework
– Hot deployment
– Dynamic API
– Metadata Integration
– Seamless integration with JBoss architecture
Aspect-Oriented Middleware
– POJO based development
– Free developers from specifications

© JBoss
JBoss,Inc.,
Inc. 2003-2005. 56

28

Você também pode gostar