Introducción a AspectJ
Mauricio Quezada
07/01/11
Lo que queremos
publicImportantcomplexMethod() {// applicationlogiconly
returnanImportantResult;
  }
Como es en realidad…
publicImportantcomplexMethod() {	LOG.log(“Enteringthemethod..”);
// complexlogic...
mutex.lock();
// ...
Aspectos
Modularizancross-cuttingconcerns
Aspectos
Modularizancross-cuttingconcerns
Logging, seguridad, sincronización, control de acceso …
Aspectos
Modularizancross-cuttingconcerns
Logging, seguridad, sincronización, control de acceso …
before(): call(complexMe...
AspectJ
Lenguaje orientado a aspectos para Java
Define su propio Join Point Model:
Joinpoints + pointcuts + advices = aspe...
¿Qué es el Join Point Model?
Es el modelo que define cuáles son los:
JoinPoints: Puntos de ejecución
Ej. Llamada de un mét...
En AspectJ
pointcutmove(): call(publicvoidFigureElement.setXY(int,int));
before(): move() {
System.out.println(“abouttomov...
Wildcards
*Account= UserAccount, AdminAccount, ...
java.*.Date = java.util.Date, java.sql.Date, ...
javax..*Model+ = Table...
Pointcuts
call(publicvoidAccount.*(int));
call(* *.*(int)) ||call(* *.*(double));
execution(public !final * *.*(..)) 
&amp...
Pointcuts
pointcutcreditOp(Accountacc, floatamt) :call (voidAccount.credit(float))
&& target (acc)
&& args...
Advices
before(): call(* Account.*(..)) { ... }
after(): call(...) { ... }
Objectaround(): move() {
// ...
Objectret = pro...
Sí capitán, estamos listos!
Ejemplos
Log
abstractaspect Log {
abstractpointcutmyClass();
pointcutmyConstr():
myClass() && execution(new(..));
pointcutm...
Log (2)
after() throwing (Error e):
myMethod() {
LOG.getInstance().write(e);
}
before(): myConstr() {
LOG.getInstance().wr...
Log (3)
publicaspectLogMyClassesextends Log {
pointcutmyClass():
within( Account ) ||
within( Dao+ ) ||
within( Controller...
TimerLog
publicabstractaspectTimerLog {
abstractpointcutmyMethod();
before(): myMethod () {
Timer.start();
System.out.prin...
Transparent RMI
public interface Receiver extendsRemote {
publicvoidreceive(Stringname, Object[] params) 	throwsRemoteExce...
Transparent RMI (2)
voidaround(Object[] arg): clientCall(arg) {
	Receiver r = null;
	r = (Receiver) Naming.lookup(“rmi://....
Access Control
aspectIdentificationperthis(this(Client)) {
publicSubjectsubject = null;
}
aspectAuthenticationpercflow(ser...
Access Control (2)
pointcutauthenticationCall(Objectcaller):
this(caller) &&
serviceRequest() &&
if(Identi...
Access Control (3)
before(Objectcaller): authenticationCall(caller) {
Identification id = 				  		Identification.aspectOf(...
Access Control (4)
aspectAuthorization {
pointcutcheckedMethods():
within(Server) &&execution(* service(..));
Obje...
Inter-Typedeclarations
declare parents: banking.entities* implementsIdentifiable;
declare warning:
: get(public !final *.*...
Cache
publicabstractaspect Cache {Map _cache = new HashMap();abstractpointcutcacheMe(Object o);Objectaround(Object o): cac...
Pero yo no programo en Java…
Pero yo no programo en Java…
<script type=“text/javascript”>
varpointcut = AspectScript.Pointcuts.call(foo);
varadvi...
Pero yo no programo en Java…
require ‘aquarium’
classAccount
includeAquarium::DSL
before :calls_to=> [:credit, :debit] ...
Otras implementaciones de aspectos
AspectC / AspectC++
AspectScript* (Javascript)
Aquarium (Ruby)
MetaclassTalk (Smalltalk...
Conclusiones
Los aspectos permiten modularizarcross-cuttingconcerns
AspectJ es un lenguaje bastante expresivo, pero limita...
Referencias
AspectJ Project http://www.eclipse.org/aspectj/
AJDT (Eclipse plugin) http://www.eclipse.org/ajdt/
Slides de C...
Upcoming SlideShare
Loading in …5
×

Introduccion a AspectJ

1,890 views

Published on

Algunos ejemplos utilizando el lenguaje de aspectos para java AspectJ

An introduction to AspectJ
Some examples using the aspect's language AspectJ

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,890
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
18
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Introduccion a AspectJ

  1. 1. Introducción a AspectJ Mauricio Quezada 07/01/11
  2. 2. Lo que queremos publicImportantcomplexMethod() {// applicationlogiconly returnanImportantResult; }
  3. 3. Como es en realidad… publicImportantcomplexMethod() { LOG.log(“Enteringthemethod..”); // complexlogic... mutex.lock(); // more complexlogic... cipher.encrypt(message); // ... Connection con = getConnection(); // ... returnanImportantResult; }
  4. 4. Aspectos Modularizancross-cuttingconcerns
  5. 5. Aspectos Modularizancross-cuttingconcerns Logging, seguridad, sincronización, control de acceso …
  6. 6. Aspectos Modularizancross-cuttingconcerns Logging, seguridad, sincronización, control de acceso … before(): call(complexMethod(..)) { LOG.log(“Callingtehmethod”); }
  7. 7. AspectJ Lenguaje orientado a aspectos para Java Define su propio Join Point Model: Joinpoints + pointcuts + advices = aspect
  8. 8. ¿Qué es el Join Point Model? Es el modelo que define cuáles son los: JoinPoints: Puntos de ejecución Ej. Llamada de un método, lanzamiento de una excepción Pointcut: Predicados que “atrapan” a los joinpoints Ej. Llamar al método foo(), lanzar una excepción de tipo Exception Advice: Acción a realizar dado un pointcut
  9. 9. En AspectJ pointcutmove(): call(publicvoidFigureElement.setXY(int,int)); before(): move() { System.out.println(“abouttomove”); } after(): move() { System.out.println(“moved”); }
  10. 10. Wildcards *Account= UserAccount, AdminAccount, ... java.*.Date = java.util.Date, java.sql.Date, ... javax..*Model+ = TableModel + subclasses+ TreeModel + subclasses + ...
  11. 11. Pointcuts call(publicvoidAccount.*(int)); call(* *.*(int)) ||call(* *.*(double)); execution(public !final * *.*(..)) &&within(Dao+);
  12. 12. Pointcuts pointcutcreditOp(Accountacc, floatamt) :call (voidAccount.credit(float)) && target (acc) && args (amt); pointcut creditOp2(Accountacc, floatamt) : execution (voidAccount.credit(float)) && this(acc) && args (amt);
  13. 13. Advices before(): call(* Account.*(..)) { ... } after(): call(...) { ... } Objectaround(): move() { // ... Objectret = proceed(); // ... returnret; }
  14. 14. Sí capitán, estamos listos! Ejemplos
  15. 15. Log abstractaspect Log { abstractpointcutmyClass(); pointcutmyConstr(): myClass() && execution(new(..)); pointcutmyMethod(): myClass() && execution(* *(..));
  16. 16. Log (2) after() throwing (Error e): myMethod() { LOG.getInstance().write(e); } before(): myConstr() { LOG.getInstance().write (“Creatingobject”); } }
  17. 17. Log (3) publicaspectLogMyClassesextends Log { pointcutmyClass(): within( Account ) || within( Dao+ ) || within( Controller ); }
  18. 18. TimerLog publicabstractaspectTimerLog { abstractpointcutmyMethod(); before(): myMethod () { Timer.start(); System.out.println( “Timerstarted at “ + t.startTime); } }
  19. 19. Transparent RMI public interface Receiver extendsRemote { publicvoidreceive(Stringname, Object[] params) throwsRemoteException; } abstractaspectTransparentRMI { abstractpointcutmyInterceptedClass(); pointcutclientCall(Object[] arg): myInterceptedClass() && execution(void *.*(..)) && args(arg);
  20. 20. Transparent RMI (2) voidaround(Object[] arg): clientCall(arg) { Receiver r = null; r = (Receiver) Naming.lookup(“rmi://...”); r.receive( thisJoinPoint.getSignature().getName(), arg); } }
  21. 21. Access Control aspectIdentificationperthis(this(Client)) { publicSubjectsubject = null; } aspectAuthenticationpercflow(serviceRequest()) { privateSubjectsubject; pointcutserviceRequest(): call(* ServerInterface+.service(..));
  22. 22. Access Control (2) pointcutauthenticationCall(Objectcaller): this(caller) && serviceRequest() && if(Identification.hasAspect(caller)); publicSubjectgetSubject() { returnsubject; }
  23. 23. Access Control (3) before(Objectcaller): authenticationCall(caller) { Identification id = Identification.aspectOf(caller); if(id.subject == null) { // askforlogin subject = id.subject; } else { throwanException; } } }
  24. 24. Access Control (4) aspectAuthorization { pointcutcheckedMethods(): within(Server) &&execution(* service(..)); Objectaround(): checkedMethods() { Authenticationauth = Authen.aspectOf(); Subjectsubject = auth.getSubject(); if(checkForPermission) returnproceed();} }
  25. 25. Inter-Typedeclarations declare parents: banking.entities* implementsIdentifiable; declare warning: : get(public !final *.*) || set(public *.*) : “Should use a getteror setter method”;
  26. 26. Cache publicabstractaspect Cache {Map _cache = new HashMap();abstractpointcutcacheMe(Object o);Objectaround(Object o): cacheMe(o) {ObjectinCache = _cache.get(o);if(inCache == null) {inCache = proceed(o); _cache.put(o, inCache); }returninCache;} }
  27. 27. Pero yo no programo en Java…
  28. 28. Pero yo no programo en Java… <script type=“text/javascript”> varpointcut = AspectScript.Pointcuts.call(foo); varadvice = function() { alert("Callingfoo"); }; AspectScript.before(pointcut, advice); </script>
  29. 29. Pero yo no programo en Java… require ‘aquarium’ classAccount includeAquarium::DSL before :calls_to=> [:credit, :debit] do |join_point, object, *args| object.balance= read_from_database… end
  30. 30. Otras implementaciones de aspectos AspectC / AspectC++ AspectScript* (Javascript) Aquarium (Ruby) MetaclassTalk (Smalltalk) Spring AOP JBoss AOP etc * hecho en Chile
  31. 31. Conclusiones Los aspectos permiten modularizarcross-cuttingconcerns AspectJ es un lenguaje bastante expresivo, pero limitado Muy útiles en ambientes de desarrollo
  32. 32. Referencias AspectJ Project http://www.eclipse.org/aspectj/ AJDT (Eclipse plugin) http://www.eclipse.org/ajdt/ Slides de CC71P – Objetos y Aspectos http://pleiad.dcc.uchile.cl/teaching/cc71p Howaspectorientedprogramming can helptobuildsecure software http://people.cs.kuleuven.be/~bart.dedecker/pubs/aspects.pdf AspectScripthttp://www.pleiad.cl/aspectscript/ Mis tareas de CC71P :-P

×