forked from spring-projects/spring-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaop.xml
More file actions
3915 lines (3167 loc) · 182 KB
/
aop.xml
File metadata and controls
3915 lines (3167 loc) · 182 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="UTF-8"?>
<chapter xml:id="aop"
xmlns="http://docbook.org/ns/docbook" version="5.0"
xmlns:xl="http://www.w3.org/1999/xlink"
xmlns:xi="http://www.w3.org/2001/XInclude"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://docbook.org/ns/docbook http://www.docbook.org/xml/5.0/xsd/docbook.xsd
http://www.w3.org/1999/xlink http://www.docbook.org/xml/5.0/xsd/xlink.xsd">
<title>Aspect Oriented Programming with Spring</title>
<section xml:id="aop-introduction">
<title>Introduction</title>
<para><emphasis>Aspect-Oriented Programming</emphasis> (AOP) complements
Object-Oriented Programming (OOP) by providing another way of thinking
about program structure. The key unit of modularity in OOP is the class,
whereas in AOP the unit of modularity is the <emphasis>aspect</emphasis>.
Aspects enable the modularization of concerns such as transaction
management that cut across multiple types and objects. (Such concerns are
often termed <emphasis>crosscutting</emphasis> concerns in AOP
literature.)</para>
<para>One of the key components of Spring is the <emphasis>AOP
framework</emphasis>. While the Spring IoC container does not depend on
AOP, meaning you do not need to use AOP if you don't want to, AOP
complements Spring IoC to provide a very capable middleware
solution.</para>
<sidebar>
<title>Spring 2.0 AOP</title>
<para>Spring 2.0 introduces a simpler and more powerful way of writing
custom aspects using either a <link linkend="aop-schema">schema-based
approach</link> or the <link linkend="aop-ataspectj">@AspectJ annotation
style</link>. Both of these styles offer fully typed advice and use of
the AspectJ pointcut language, while still using Spring AOP for
weaving.</para>
<para>The Spring 2.0 schema- and @AspectJ-based AOP support is discussed
in this chapter. Spring 2.0 AOP remains fully backwards compatible with
Spring 1.2 AOP, and the lower-level AOP support offered by the Spring
1.2 APIs is discussed in <link linkend="aop-api">the following
chapter</link>.</para>
</sidebar>
<para>AOP is used in the Spring Framework to...</para>
<itemizedlist>
<listitem>
<para>... provide declarative enterprise services, especially as a
replacement for EJB declarative services. The most important such
service is <link
linkend="transaction-declarative"><emphasis>declarative transaction
management</emphasis></link>.</para>
</listitem>
<listitem>
<para>... allow users to implement custom aspects, complementing their
use of OOP with AOP.</para>
</listitem>
</itemizedlist>
<remark>If you are interested only in generic declarative services
or other pre-packaged declarative middleware services such as pooling, you
do not need to work directly with Spring AOP, and can skip most of this
chapter.</remark>
<section xml:id="aop-introduction-defn">
<title>AOP concepts</title>
<para>Let us begin by defining some central AOP concepts and
terminology. These terms are not Spring-specific... unfortunately, AOP
terminology is not particularly intuitive; however, it would be even
more confusing if Spring used its own terminology.</para>
<itemizedlist>
<listitem>
<para><emphasis>Aspect</emphasis>: a modularization of a concern
that cuts across multiple classes. Transaction management is a good
example of a crosscutting concern in enterprise Java applications.
In Spring AOP, aspects are implemented using regular classes (the
<link linkend="aop-schema">schema-based approach</link>) or regular
classes annotated with the <interfacename>@Aspect</interfacename>
annotation (the <link
linkend="aop-ataspectj"><interfacename>@AspectJ</interfacename>
style</link>).</para>
</listitem>
<listitem>
<para><emphasis>Join point</emphasis>: a point during the execution
of a program, such as the execution of a method or the handling of
an exception. In Spring AOP, a join point
<emphasis>always</emphasis> represents a method execution.</para>
</listitem>
<listitem>
<para><emphasis>Advice</emphasis>: action taken by an aspect at a
particular join point. Different types of advice include "around,"
"before" and "after" advice. (Advice types are discussed below.)
Many AOP frameworks, including Spring, model an advice as an
<emphasis>interceptor</emphasis>, maintaining a chain of
interceptors <emphasis>around</emphasis> the join point.</para>
</listitem>
<listitem>
<para><emphasis>Pointcut</emphasis>: a predicate that matches join
points. Advice is associated with a pointcut expression and runs at
any join point matched by the pointcut (for example, the execution
of a method with a certain name). The concept of join points as
matched by pointcut expressions is central to AOP, and Spring uses
the AspectJ pointcut expression language by default.</para>
</listitem>
<listitem>
<para><emphasis>Introduction</emphasis>: declaring additional
methods or fields on behalf of a type. Spring AOP allows you to
introduce new interfaces (and a corresponding implementation) to any
advised object. For example, you could use an introduction to make a
bean implement an <interfacename>IsModified</interfacename>
interface, to simplify caching. (An introduction is known as an
inter-type declaration in the AspectJ community.)</para>
</listitem>
<listitem>
<para><emphasis>Target object</emphasis>: object being advised by
one or more aspects. Also referred to as the
<emphasis>advised</emphasis> object. Since Spring AOP is implemented
using runtime proxies, this object will always be a
<emphasis>proxied</emphasis> object.</para>
</listitem>
<listitem>
<para><emphasis>AOP proxy</emphasis>: an object created by the AOP
framework in order to implement the aspect contracts (advise method
executions and so on). In the Spring Framework, an AOP proxy will be
a JDK dynamic proxy or a CGLIB proxy.</para>
</listitem>
<listitem>
<para><emphasis>Weaving</emphasis>: linking aspects with other
application types or objects to create an advised object. This can
be done at compile time (using the AspectJ compiler, for example),
load time, or at runtime. Spring AOP, like other pure Java AOP
frameworks, performs weaving at runtime.</para>
</listitem>
</itemizedlist>
<para>Types of advice:</para>
<itemizedlist>
<listitem>
<para><emphasis>Before advice</emphasis>: Advice that executes
before a join point, but which does not have the ability to prevent
execution flow proceeding to the join point (unless it throws an
exception).</para>
</listitem>
<listitem>
<para><emphasis>After returning advice</emphasis>: Advice to be
executed after a join point completes normally: for example, if a
method returns without throwing an exception.</para>
</listitem>
<listitem>
<para><emphasis>After throwing advice</emphasis>: Advice to be
executed if a method exits by throwing an exception.</para>
</listitem>
<listitem>
<para><emphasis>After (finally) advice</emphasis>: Advice to be
executed regardless of the means by which a join point exits (normal
or exceptional return).</para>
</listitem>
<listitem>
<para><emphasis>Around advice</emphasis>: Advice that surrounds a
join point such as a method invocation. This is the most powerful
kind of advice. Around advice can perform custom behavior before and
after the method invocation. It is also responsible for choosing
whether to proceed to the join point or to shortcut the advised
method execution by returning its own return value or throwing an
exception.</para>
</listitem>
</itemizedlist>
<para>Around advice is the most general kind of advice. Since Spring
AOP, like AspectJ, provides a full range of advice types, we recommend
that you use the least powerful advice type that can implement the
required behavior. For example, if you need only to update a cache with
the return value of a method, you are better off implementing an after
returning advice than an around advice, although an around advice can
accomplish the same thing. Using the most specific advice type provides
a simpler programming model with less potential for errors. For example,
you do not need to invoke the <methodname>proceed()</methodname> method
on the <interfacename>JoinPoint</interfacename> used for around advice,
and hence cannot fail to invoke it.</para>
<para>In Spring 2.0, all advice parameters are statically typed, so that
you work with advice parameters of the appropriate type (the type of the
return value from a method execution for example) rather than
<classname>Object</classname> arrays.</para>
<para>The concept of join points, matched by pointcuts, is the key to
AOP which distinguishes it from older technologies offering only
interception. Pointcuts enable advice to be targeted independently of
the Object-Oriented hierarchy. For example, an around advice providing
declarative transaction management can be applied to a set of methods
spanning multiple objects (such as all business operations in the
service layer).</para>
</section>
<section xml:id="aop-introduction-spring-defn">
<title>Spring AOP capabilities and goals</title>
<para>Spring AOP is implemented in pure Java. There is no need for a
special compilation process. Spring AOP does not need to control the
class loader hierarchy, and is thus suitable for use in a Servlet
container or application server.</para>
<para>Spring AOP currently supports only method execution join points
(advising the execution of methods on Spring beans). Field interception
is not implemented, although support for field interception could be
added without breaking the core Spring AOP APIs. If you need to advise
field access and update join points, consider a language such as
AspectJ.</para>
<para>Spring AOP's approach to AOP differs from that of most other AOP
frameworks. The aim is not to provide the most complete AOP
implementation (although Spring AOP is quite capable); it is rather to
provide a close integration between AOP implementation and Spring IoC to
help solve common problems in enterprise applications.</para>
<para>Thus, for example, the Spring Framework's AOP functionality is
normally used in conjunction with the Spring IoC container. Aspects are
configured using normal bean definition syntax (although this allows
powerful "autoproxying" capabilities): this is a crucial difference from
other AOP implementations. There are some things you cannot do easily or
efficiently with Spring AOP, such as advise very fine-grained objects
(such as domain objects typically): AspectJ is the best choice in such
cases. However, our experience is that Spring AOP provides an excellent
solution to most problems in enterprise Java applications that are
amenable to AOP.</para>
<para>Spring AOP will never strive to compete with AspectJ to provide a
comprehensive AOP solution. We believe that both proxy-based frameworks
like Spring AOP and full-blown frameworks such as AspectJ are valuable,
and that they are complementary, rather than in competition. Spring 2.0
seamlessly integrates Spring AOP and IoC with AspectJ, to enable all
uses of AOP to be catered for within a consistent Spring-based
application architecture. This integration does not affect the Spring
AOP API or the AOP Alliance API: Spring AOP remains backward-compatible.
See <link linkend="aop-api">the following chapter</link> for a
discussion of the Spring AOP APIs.</para>
<note>
<para>One of the central tenets of the Spring Framework is that of
<emphasis>non-invasiveness</emphasis>; this is the idea that you
should not be forced to introduce framework-specific classes and
interfaces into your business/domain model. However, in some places
the Spring Framework does give you the option to introduce Spring
Framework-specific dependencies into your codebase: the rationale in
giving you such options is because in certain scenarios it might be
just plain easier to read or code some specific piece of functionality
in such a way. The Spring Framework (almost) always offers you the
choice though: you have the freedom to make an informed decision as to
which option best suits your particular use case or scenario.</para>
<para>One such choice that is relevant to this chapter is that of
which AOP framework (and which AOP style) to choose. You have the
choice of AspectJ and/or Spring AOP, and you also have the choice of
either the @AspectJ annotation-style approach or the Spring XML
configuration-style approach. The fact that this chapter chooses to
introduce the @AspectJ-style approach first should not be taken as an
indication that the Spring team favors the @AspectJ annotation-style
approach over the Spring XML configuration-style.</para>
<para>See <xref linkend="aop-choosing" /> for a
more complete discussion of the whys and wherefores of each style.</para>
</note>
</section>
<section xml:id="aop-introduction-proxies">
<title>AOP Proxies</title>
<para>Spring AOP defaults to using standard J2SE <emphasis>dynamic
proxies</emphasis> for AOP proxies. This enables any interface (or set
of interfaces) to be proxied.</para>
<para>Spring AOP can also use CGLIB proxies. This is necessary to proxy
classes, rather than interfaces. CGLIB is used by default if a business
object does not implement an interface. As it is good practice to
program to interfaces rather than classes, business classes normally
will implement one or more business interfaces. It is possible to <link
linkend="aop-autoproxy-force-CGLIB">force the use of CGLIB</link>, in
those (hopefully rare) cases where you need to advise a method that is
not declared on an interface, or where you need to pass a proxied object
to a method as a concrete type.</para>
<para>It is important to grasp the fact that Spring AOP is
<emphasis>proxy-based</emphasis>. See <xref
linkend="aop-understanding-aop-proxies" /> for a thorough examination of
exactly what this implementation detail actually means.</para>
</section>
</section>
<section xml:id="aop-ataspectj">
<title>@AspectJ support</title>
<para>@AspectJ refers to a style of declaring aspects as regular Java
classes annotated with Java 5 annotations. The @AspectJ style was
introduced by the <link xl:href="http://www.eclipse.org/aspectj">AspectJ
project</link> as part of the AspectJ 5 release. Spring 2.0 interprets
the same annotations as AspectJ 5, using a library supplied by AspectJ for
pointcut parsing and matching. The AOP runtime is still pure Spring AOP
though, and there is no dependency on the AspectJ compiler or
weaver.</para>
<remark>Using the AspectJ compiler and weaver enables use of the
full AspectJ language, and is discussed in <xref
linkend="aop-using-aspectj" />.</remark>
<section xml:id="aop-aspectj-support">
<title>Enabling @AspectJ Support</title>
<para>To use @AspectJ aspects in a Spring configuration you need to
enable Spring support for configuring Spring AOP based on @AspectJ
aspects, and <emphasis>autoproxying</emphasis> beans based on whether or
not they are advised by those aspects. By autoproxying we mean that if
Spring determines that a bean is advised by one or more aspects, it will
automatically generate a proxy for that bean to intercept method
invocations and ensure that advice is executed as needed.</para>
<para>The @AspectJ support can be enabled with XML or Java style
configuration. In either case you will also need to ensure that
AspectJ's <filename class="libraryfile">aspectjweaver.jar</filename>
library is on the classpath of your application (version 1.6.8 or later).
This library is available in the <filename class="directory">'lib'</filename>
directory of an AspectJ distribution or via the Maven Central repository.</para>
<section xml:id="aop-enable-aspectj-java">
<title>Enabling @AspectJ Support with Java configuration</title>
<para>To enable @AspectJ support with Java
<interfacename>@Configuration</interfacename> add the
<interfacename>@EnableAspectJAutoProxy</interfacename> annotation:</para>
<programlisting language="java">@Configuration
@EnableAspectJAutoProxy
public class AppConfig {
}</programlisting>
</section>
<section xml:id="aop-enable-aspectj-xml">
<title>Enabling @AspectJ Support with XML configuration</title>
<para>To enable @AspectJ support with XML based configuration use the
<literal>aop:aspectj-autoproxy</literal> element:</para>
<programlisting language="xml"><aop:aspectj-autoproxy/></programlisting>
<para>This assumes that you are using schema support as described in
<xref linkend="xsd-config" />. See <xref
linkend="xsd-config-body-schemas-aop" /> for how to import the tags in
the aop namespace.</para>
<para>If you are using the DTD, it is still possible to enable @AspectJ
support by adding the following definition to your application
context:</para>
<programlisting language="xml"><bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" /></programlisting>
</section>
</section>
<section xml:id="aop-at-aspectj">
<title>Declaring an aspect</title>
<para>With the @AspectJ support enabled, any bean defined in your
application context with a class that is an @AspectJ aspect (has the
<interfacename>@Aspect</interfacename> annotation) will be automatically
detected by Spring and used to configure Spring AOP. The following
example shows the minimal definition required for a not-very-useful
aspect:</para>
<para>A regular bean definition in the application context, pointing to
a bean class that has the <interfacename>@Aspect</interfacename>
annotation:</para>
<programlisting language="xml"><bean id="myAspect" class="org.xyz.NotVeryUsefulAspect">
<lineannotation><!-- configure properties of aspect here as normal --></lineannotation>
</bean>
</programlisting>
<para>And the <classname>NotVeryUsefulAspect</classname> class
definition, annotated with
<interfacename>org.aspectj.lang.annotation.Aspect</interfacename>
annotation;</para>
<programlisting language="java">package org.xyz;
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class NotVeryUsefulAspect {
}</programlisting>
<para>Aspects (classes annotated with
<interfacename>@Aspect</interfacename>) may have methods and fields just
like any other class. They may also contain pointcut, advice, and
introduction (inter-type) declarations.</para>
<note>
<title>Autodetecting aspects through component scanning</title>
<para>You may register aspect classes as regular beans in your Spring
XML configuration, or autodetect them through classpath scanning -
just like any other Spring-managed bean. However, note that the
<emphasis>@Aspect</emphasis> annotation is <emphasis>not</emphasis>
sufficient for autodetection in the classpath: For that purpose,
you need to add a separate <emphasis>@Component</emphasis> annotation
(or alternatively a custom stereotype annotation that qualifies,
as per the rules of Spring's component scanner).</para>
</note>
<note>
<title>Advising aspects with other aspects?</title>
<para>In Spring AOP, it is <emphasis>not</emphasis> possible to have
aspects themselves be the target of advice from other aspects. The
<emphasis>@Aspect</emphasis> annotation on a class marks it as an
aspect, and hence excludes it from auto-proxying.</para>
</note>
</section>
<section xml:id="aop-pointcuts">
<title>Declaring a pointcut</title>
<para>Recall that pointcuts determine join points of interest, and thus
enable us to control when advice executes. <emphasis>Spring AOP only
supports method execution join points for Spring beans</emphasis>, so
you can think of a pointcut as matching the execution of methods on
Spring beans. A pointcut declaration has two parts: a signature
comprising a name and any parameters, and a pointcut expression that
determines <emphasis>exactly</emphasis> which method executions we are
interested in. In the @AspectJ annotation-style of AOP, a pointcut
signature is provided by a regular method definition, and the pointcut
expression is indicated using the
<interfacename>@Pointcut</interfacename> annotation (the method serving
as the pointcut signature <emphasis>must</emphasis> have a
<literal>void</literal> return type).</para>
<para>An example will help make this distinction between a pointcut
signature and a pointcut expression clear. The following example defines
a pointcut named <literal>'anyOldTransfer'</literal> that will match the
execution of any method named <literal>'transfer'</literal>:</para>
<programlisting language="java">@Pointcut("execution(* transfer(..))")<lineannotation>// the pointcut expression</lineannotation>
private void anyOldTransfer() {}<lineannotation>// the pointcut signature</lineannotation></programlisting>
<para>The pointcut expression that forms the value of the
<interfacename>@Pointcut</interfacename> annotation is a regular AspectJ
5 pointcut expression. For a full discussion of AspectJ's pointcut
language, see the <link
xl:href="http://www.eclipse.org/aspectj/doc/released/progguide/index.html">AspectJ
Programming Guide</link> (and for Java 5 based extensions, the <link
xl:href="http://www.eclipse.org/aspectj/doc/released/adk15notebook/index.html">AspectJ
5 Developers Notebook</link>) or one of the books on AspectJ such as
<quote>Eclipse AspectJ</quote> by Colyer et. al. or <quote>AspectJ in
Action</quote> by Ramnivas Laddad.</para>
<section xml:id="aop-pointcuts-designators">
<title>Supported Pointcut Designators</title>
<para>Spring AOP supports the following AspectJ pointcut designators
(PCD) for use in pointcut expressions:</para>
<sidebar>
<title>Other pointcut types</title>
<para>The full AspectJ pointcut language supports additional
pointcut designators that are not supported in Spring. These are:
<literal>call, get, set, preinitialization, staticinitialization,
initialization, handler, adviceexecution, withincode, cflow,
cflowbelow, if, @this</literal>, and <literal>@withincode</literal>.
Use of these pointcut designators in pointcut expressions
interpreted by Spring AOP will result in an
<classname>IllegalArgumentException</classname> being thrown.</para>
<para>The set of pointcut designators supported by Spring AOP may be
extended in future releases to support more of the AspectJ pointcut
designators.</para>
</sidebar>
<itemizedlist>
<listitem>
<para><emphasis>execution</emphasis> - for matching method
execution join points, this is the primary pointcut designator you
will use when working with Spring AOP</para>
</listitem>
<listitem>
<para><emphasis>within</emphasis> - limits matching to join points
within certain types (simply the execution of a method declared
within a matching type when using Spring AOP)</para>
</listitem>
<listitem>
<para><emphasis>this</emphasis> - limits matching to join points
(the execution of methods when using Spring AOP) where the bean
reference (Spring AOP proxy) is an instance of the given
type</para>
</listitem>
<listitem>
<para><emphasis>target</emphasis> - limits matching to join points
(the execution of methods when using Spring AOP) where the target
object (application object being proxied) is an instance of the
given type</para>
</listitem>
<listitem>
<para><emphasis>args</emphasis> - limits matching to join points
(the execution of methods when using Spring AOP) where the
arguments are instances of the given types</para>
</listitem>
<listitem>
<para><emphasis><interfacename>@target</interfacename></emphasis>
- limits matching to join points (the execution of methods when
using Spring AOP) where the class of the executing object has an
annotation of the given type</para>
</listitem>
<listitem>
<para><emphasis><interfacename>@args</interfacename></emphasis> -
limits matching to join points (the execution of methods when
using Spring AOP) where the runtime type of the actual arguments
passed have annotations of the given type(s)</para>
</listitem>
<listitem>
<para><emphasis><interfacename>@within</interfacename></emphasis>
- limits matching to join points within types that have the given
annotation (the execution of methods declared in types with the
given annotation when using Spring AOP)</para>
</listitem>
<listitem>
<para><emphasis>@annotation</emphasis> - limits matching to join
points where the subject of the join point (method being executed
in Spring AOP) has the given annotation</para>
</listitem>
</itemizedlist>
<para>Because Spring AOP limits matching to only method execution
join points, the discussion of the pointcut designators above gives a
narrower definition than you will find in the AspectJ programming
guide. In addition, AspectJ itself has type-based semantics and at an
execution join point both '<literal>this</literal>' and
'<literal>target</literal>' refer to the same object - the object
executing the method. Spring AOP is a proxy-based system and
differentiates between the proxy object itself (bound to
'<literal>this</literal>') and the target object behind the proxy
(bound to '<literal>target</literal>').</para>
<note>
<para>Due to the proxy-based nature of Spring's AOP framework,
protected methods are by definition <emphasis>not</emphasis>
intercepted, neither for JDK proxies (where this isn't applicable)
nor for CGLIB proxies (where this is technically possible but not
recommendable for AOP purposes). As a consequence, any given pointcut
will be matched against <emphasis>public methods only</emphasis>!</para>
<para>If your interception needs include protected/private methods
or even constructors, consider the use of Spring-driven
<link linkend="aop-aj-ltw">native AspectJ weaving</link> instead
of Spring's proxy-based AOP framework. This constitutes a different
mode of AOP usage with different characteristics, so be sure to make
yourself familiar with weaving first before making a decision.</para>
</note>
<para>Spring AOP also supports an additional PCD named
'<literal>bean</literal>'. This PCD allows you to limit the matching
of join points to a particular named Spring bean, or to a set of named
Spring beans (when using wildcards). The '<literal>bean</literal>' PCD
has the following form:</para>
<programlisting language="java">bean(idOrNameOfBean)</programlisting>
<para>The '<literal>idOrNameOfBean</literal>' token can be the name of
any Spring bean: limited wildcard support using the
'<literal>*</literal>' character is provided, so if you establish
some naming conventions for your Spring beans you can quite easily
write a '<literal>bean</literal>' PCD expression to pick them out. As
is the case with other pointcut designators, the
'<literal>bean</literal>' PCD can be &&'ed, ||'ed, and !
(negated) too.</para>
<note>
<para>Please note that the '<literal>bean</literal>' PCD is
<emphasis>only</emphasis> supported in Spring AOP - and
<emphasis>not</emphasis> in native AspectJ weaving. It is a
Spring-specific extension to the standard PCDs that AspectJ
defines.</para>
<para>The '<literal>bean</literal>' PCD operates at the
<emphasis>instance</emphasis> level (building on the Spring
bean name concept) rather than at the type level only
(which is what weaving-based AOP is limited to).
Instance-based pointcut designators are a special capability
of Spring's proxy-based AOP framework and its close integration
with the Spring bean factory, where it is natural and
straightforward to identify specific beans by name.</para>
</note>
</section>
<section xml:id="aop-pointcuts-combining">
<title>Combining pointcut expressions</title>
<para>Pointcut expressions can be combined using '&&', '||'
and '!'. It is also possible to refer to pointcut expressions by name.
The following example shows three pointcut expressions:
<literal>anyPublicOperation</literal> (which matches if a method
execution join point represents the execution of any public method);
<literal>inTrading</literal> (which matches if a method execution is
in the trading module), and <literal>tradingOperation</literal> (which
matches if a method execution represents any public method in the
trading module).</para>
<programlisting language="java"> @Pointcut("execution(public * *(..))")
private void anyPublicOperation() {}
@Pointcut("within(com.xyz.someapp.trading..*)")
private void inTrading() {}
@Pointcut("anyPublicOperation() && inTrading()")
private void tradingOperation() {}</programlisting>
<para>It is a best practice to build more complex pointcut expressions
out of smaller named components as shown above. When referring to
pointcuts by name, normal Java visibility rules apply (you can see
private pointcuts in the same type, protected pointcuts in the
hierarchy, public pointcuts anywhere and so on). Visibility does not
affect pointcut <emphasis>matching</emphasis>.</para>
</section>
<section xml:id="aop-common-pointcuts">
<title>Sharing common pointcut definitions</title>
<para>When working with enterprise applications, you often want to
refer to modules of the application and particular sets of operations
from within several aspects. We recommend defining a
"SystemArchitecture" aspect that captures common pointcut expressions
for this purpose. A typical such aspect would look as follows:</para>
<programlisting language="java">package com.xyz.someapp;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class SystemArchitecture {
<lineannotation>/**
* A join point is in the web layer if the method is defined
* in a type in the com.xyz.someapp.web package or any sub-package
* under that.
*/</lineannotation>
@Pointcut("within(com.xyz.someapp.web..*)")
public void inWebLayer() {}
<lineannotation>/**
* A join point is in the service layer if the method is defined
* in a type in the com.xyz.someapp.service package or any sub-package
* under that.
*/</lineannotation>
@Pointcut("within(com.xyz.someapp.service..*)")
public void inServiceLayer() {}
<lineannotation>/**
* A join point is in the data access layer if the method is defined
* in a type in the com.xyz.someapp.dao package or any sub-package
* under that.
*/</lineannotation>
@Pointcut("within(com.xyz.someapp.dao..*)")
public void inDataAccessLayer() {}
<lineannotation>/**
* A business service is the execution of any method defined on a service
* interface. This definition assumes that interfaces are placed in the
* "service" package, and that implementation types are in sub-packages.
*
* If you group service interfaces by functional area (for example,
* in packages com.xyz.someapp.abc.service and com.xyz.def.service) then
* the pointcut expression "execution(* com.xyz.someapp..service.*.*(..))"
* could be used instead.
*
* Alternatively, you can write the expression using the 'bean'
* PCD, like so "bean(*Service)". (This assumes that you have
* named your Spring service beans in a consistent fashion.)
*/</lineannotation>
@Pointcut("execution(* com.xyz.someapp.service.*.*(..))")
public void businessService() {}
<lineannotation>/**
* A data access operation is the execution of any method defined on a
* dao interface. This definition assumes that interfaces are placed in the
* "dao" package, and that implementation types are in sub-packages.
*/</lineannotation>
@Pointcut("execution(* com.xyz.someapp.dao.*.*(..))")
public void dataAccessOperation() {}
}</programlisting>
<para>The pointcuts defined in such an aspect can be referred to
anywhere that you need a pointcut expression. For example, to make the
service layer transactional, you could write:</para>
<programlisting language="xml"><aop:config>
<aop:advisor
pointcut="com.xyz.someapp.SystemArchitecture.businessService()"
advice-ref="tx-advice"/>
</aop:config>
<tx:advice id="tx-advice">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice></programlisting>
<para>The <literal><aop:config></literal> and
<literal><aop:advisor></literal> elements are discussed in <xref
linkend="aop-schema" />. The transaction elements are discussed in
<xref linkend="transaction" />.</para>
</section>
<section xml:id="aop-pointcuts-examples">
<title>Examples</title>
<para>Spring AOP users are likely to use the
<literal>execution</literal> pointcut designator the most often. The
format of an execution expression is:</para>
<programlisting language="java">execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern)
throws-pattern?)</programlisting>
<para>All parts except the returning type pattern (ret-type-pattern in
the snippet above), name pattern, and parameters pattern are optional.
The returning type pattern determines what the return type of the
method must be in order for a join point to be matched. Most
frequently you will use <literal>*</literal> as the returning type
pattern, which matches any return type. A fully-qualified type name
will match only when the method returns the given type. The name
pattern matches the method name. You can use the <literal>*</literal>
wildcard as all or part of a name pattern. The parameters pattern is
slightly more complex: <literal>()</literal> matches a method that
takes no parameters, whereas <literal>(..)</literal> matches any
number of parameters (zero or more). The pattern
<literal>(*)</literal> matches a method taking one parameter of any
type, <literal>(*,String)</literal> matches a method taking two
parameters, the first can be of any type, the second must be a String.
Consult the <link
xl:href="http://www.eclipse.org/aspectj/doc/released/progguide/semantics-pointcuts.html">
Language Semantics</link> section of the AspectJ Programming Guide
for more information.</para>
<para>Some examples of common pointcut expressions are given
below.</para>
<itemizedlist>
<listitem>
<para>the execution of any public method:</para>
<programlisting language="java">execution(public * *(..))</programlisting>
</listitem>
<listitem>
<para>the execution of any method with a name beginning with
"set":</para>
<programlisting language="java">execution(* set*(..))</programlisting>
</listitem>
<listitem>
<para>the execution of any method defined by the
<interfacename>AccountService</interfacename> interface:</para>
<programlisting language="java">execution(* com.xyz.service.AccountService.*(..))</programlisting>
</listitem>
<listitem>
<para>the execution of any method defined in the service
package:</para>
<programlisting language="java">execution(* com.xyz.service.*.*(..))</programlisting>
</listitem>
<listitem>
<para>the execution of any method defined in the service package
or a sub-package:</para>
<programlisting language="java">execution(* com.xyz.service..*.*(..))</programlisting>
</listitem>
<listitem>
<para>any join point (method execution only in Spring AOP) within
the service package:</para>
<programlisting language="java">within(com.xyz.service.*)</programlisting>
</listitem>
<listitem>
<para>any join point (method execution only in Spring AOP) within
the service package or a sub-package:</para>
<programlisting language="java">within(com.xyz.service..*)</programlisting>
</listitem>
<listitem>
<para>any join point (method execution only in Spring AOP) where
the proxy implements the
<interfacename>AccountService</interfacename> interface:</para>
<programlisting language="java">this(com.xyz.service.AccountService)</programlisting>
<remark>'this' is more commonly used in a binding form :-
see the following section on advice for how to make the proxy
object available in the advice body.</remark>
</listitem>
<listitem>
<para>any join point (method execution only in Spring AOP) where
the target object implements the
<interfacename>AccountService</interfacename> interface:</para>
<programlisting language="java">target(com.xyz.service.AccountService)</programlisting>
<remark>'target' is more commonly used in a binding form :-
see the following section on advice for how to make the target
object available in the advice body.</remark>
</listitem>
<listitem>
<para>any join point (method execution only in Spring AOP) which
takes a single parameter, and where the argument passed at runtime
is <interfacename>Serializable</interfacename>:</para>
<programlisting language="java">args(java.io.Serializable)</programlisting>
<remark>'args' is more commonly used in a binding form :- see the
following section on advice for how to make the method arguments
available in the advice body.</remark>
<para>Note that the pointcut given in this example is different to
<literal>execution(* *(java.io.Serializable))</literal>: the args
version matches if the argument passed at runtime is Serializable,
the execution version matches if the method signature declares a
single parameter of type
<interfacename>Serializable</interfacename>.</para>
</listitem>
<listitem>
<para>any join point (method execution only in Spring AOP) where
the target object has an
<interfacename>@Transactional</interfacename> annotation:</para>
<programlisting language="java">@target(org.springframework.transaction.annotation.Transactional)</programlisting>
<remark>'@target' can also be used in a binding form :- see
the following section on advice for how to make the annotation
object available in the advice body.</remark>
</listitem>
<listitem>
<para>any join point (method execution only in Spring AOP) where
the declared type of the target object has an
<interfacename>@Transactional</interfacename> annotation:</para>
<programlisting language="java">@within(org.springframework.transaction.annotation.Transactional)</programlisting>
<remark>'@within' can also be used in a binding form :- see
the following section on advice for how to make the annotation
object available in the advice body.</remark>
</listitem>
<listitem>
<para>any join point (method execution only in Spring AOP) where
the executing method has an
<interfacename>@Transactional</interfacename> annotation:</para>
<programlisting language="java">@annotation(org.springframework.transaction.annotation.Transactional)</programlisting>
<remark>'@annotation' can also be used in a binding form :-
see the following section on advice for how to make the annotation
object available in the advice body.</remark>
</listitem>
<listitem>
<para>any join point (method execution only in Spring AOP) which
takes a single parameter, and where the runtime type of the
argument passed has the <interfacename>@Classified</interfacename>
annotation:</para>
<programlisting language="java">@args(com.xyz.security.Classified)</programlisting>
<remark>'@args' can also be used in a binding form :- see
the following section on advice for how to make the annotation
object(s) available in the advice body.</remark>
</listitem>
<listitem>
<para>any join point (method execution only in Spring AOP) on a
Spring bean named '<literal>tradeService</literal>':</para>
<programlisting language="java">bean(tradeService)</programlisting>
</listitem>
<listitem>
<para>any join point (method execution only in Spring AOP) on
Spring beans having names that match the wildcard expression
'<literal>*Service</literal>':</para>
<programlisting language="java">bean(*Service)</programlisting>
</listitem>
</itemizedlist>
</section>
<section xml:id="writing-good-pointcuts">
<title>Writing good pointcuts</title>
<para>During compilation, AspectJ processes pointcuts in order to try and optimize matching performance. Examining code
and determining if each join point matches (statically or dynamically) a given pointcut is a costly process. (A dynamic
match means the match cannot be fully determined from static analysis and a test will be placed in the code to
determine if there is an actual match when the code is running). On first encountering a pointcut declaration,
AspectJ will rewrite it into an optimal form for the matching process. What does this mean? Basically pointcuts
are rewritten in DNF (Disjunctive Normal Form) and the components of the pointcut are sorted such that those
components that are cheaper to evaluate are checked first. This means you do not have to worry about understanding
the performance of various pointcut designators and may supply them in any order in a pointcut declaration.</para>
<para>However, AspectJ can only work with what it is told, and for optimal performance of matching you should
think about what they are trying to achieve and narrow the search space for matches as much as possible in the
definition. The existing designators naturally fall into one of three groups: kinded, scoping and context:</para>
<itemizedlist>
<listitem><para>Kinded designators are those which select a particular kind of join point. For example: execution, get, set, call, handler</para></listitem>
<listitem><para>Scoping designators are those which select a group of join points of interest (of probably many kinds). For example: within, withincode</para></listitem>
<listitem><para>Contextual designators are those that match (and optionally bind) based on context. For example: this, target, @annotation</para></listitem>
</itemizedlist>
<para>A well written pointcut should try and include at least the first two types (kinded and scoping), whilst
the contextual designators may be included if wishing to match based on join point context, or bind that context
for use in the advice. Supplying either just a kinded designator or just a contextual designator will work but
could affect weaving performance (time and memory used) due to all the extra processing and analysis. Scoping
designators are very fast to match and their usage means AspectJ can very quickly dismiss groups of
join points that should not be further processed - that is why a good pointcut should always include
one if possible.</para>
</section>
</section>
<section xml:id="aop-advice">
<title>Declaring advice</title>
<para>Advice is associated with a pointcut expression, and runs before,
after, or around method executions matched by the pointcut. The pointcut
expression may be either a simple reference to a named pointcut, or a
pointcut expression declared in place.</para>
<section xml:id="aop-advice-before">
<title>Before advice</title>
<para>Before advice is declared in an aspect using the
<interfacename>@Before</interfacename> annotation:</para>
<programlisting language="java">import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class BeforeExample {
@Before("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
public void doAccessCheck() {
<lineannotation>// ...</lineannotation>
}
}</programlisting>
<para>If using an in-place pointcut expression we could rewrite the
above example as:</para>
<programlisting language="java">import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class BeforeExample {
@Before("execution(* com.xyz.myapp.dao.*.*(..))")
public void doAccessCheck() {
<lineannotation>// ...</lineannotation>
}
}</programlisting>