{"id":632,"date":"2020-09-27T05:10:40","date_gmt":"2020-09-27T02:10:40","guid":{"rendered":"https:\/\/aliyargunes.space\/blog\/?p=632"},"modified":"2020-09-27T05:10:40","modified_gmt":"2020-09-27T02:10:40","slug":"aspect-oriented-programming-notes-2-setting-up-aop-dependencies-and-declaring-aspects-advices-pointcuts","status":"publish","type":"post","link":"https:\/\/aliyargunes.com.tr\/blog\/aspect-oriented-programming-notes-2-setting-up-aop-dependencies-and-declaring-aspects-advices-pointcuts\/","title":{"rendered":"Aspect Oriented Programming Notes #2: Setting Up AOP Dependencies and Declaring Aspects, Advices, Pointcuts"},"content":{"rendered":"\n<div class=\"wp-block-image\"><figure class=\"alignleft size-medium is-resized\"><a href=\"https:\/\/aliyargunes.com.tr\/blog\/wp-content\/uploads\/2020\/09\/spring-aop-diagram.jpg\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/aliyargunes.com.tr\/blog\/wp-content\/uploads\/2020\/09\/spring-aop-diagram-300x272.jpg\" alt=\"\" class=\"wp-image-675\" width=\"300\" height=\"272\" srcset=\"https:\/\/aliyargunes.com.tr\/blog\/wp-content\/uploads\/2020\/09\/spring-aop-diagram-300x272.jpg 300w, https:\/\/aliyargunes.com.tr\/blog\/wp-content\/uploads\/2020\/09\/spring-aop-diagram.jpg 410w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/a><\/figure><\/div>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>An <strong>aspect<\/strong> is a Java class that modularizes a set of concerns (e.g., logging or transaction management) that cuts across multiple types and objects. Java classes that modularize such concerns are decorated with the <code>@Aspect<\/code> annotation. In AOP terminology, aspects are also complemented by <strong>advices<\/strong>, which in themselves have <strong>pointcuts<\/strong>. <\/p><p>An<strong> advice<\/strong> is a simple Java method with one of the advice annotations. AspectJ supports five types of advice annotations: <\/p><p><code>@Before<\/code>, <code>@After<\/code>, <code>@AfterReturning<\/code>, <code>@AfterThrowing,<\/code> and <code>@Around<\/code>. <\/p><p>A <strong>pointcut<\/strong> is an expression that looks for types and objects on which to apply the aspect\u2019s advices.<\/p><cite>Spring 5 Recipes: A Problem-Solution Approach, Marten Deinum, Daniel Rubio, and Josh Long, APress Springer, 2017<\/cite><\/blockquote>\n\n\n\n<p>For testing the aspects write a simple calculator interface like this:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\npublic interface ArithmeticCalculator {\n\n\tpublic double add(double a, double b);\n\tpublic double sub(double a, double b);\n\tpublic double mul(double a, double b);\n\tpublic double div(double a, double b);\n\n}\n<\/pre><\/div>\n\n\n<p>Then implementation of this interface:<\/p>\n\n\n\n<!--more-->\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\nimport org.springframework.stereotype.Component;\n\n@Component(&quot;arithmeticCalculator&quot;)\npublic class ArithmeticCalculatorImpl implements ArithmeticCalculator {\n\n\t@Override\n\tpublic double add(double a, double b) {\n\t\tdouble result = a + b;\n\t\tSystem.out.println(a + &quot; + &quot; + b + &quot; = &quot; + result);\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic double sub(double a, double b) {\n\t\tdouble result = a - b;\n\t\tSystem.out.println(a + &quot; - &quot; +\n\t\t b + &quot; = &quot; + result);\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic double mul(double a, double b) {\n\t\tdouble result = a * b;\n\t\tSystem.out.println(a + &quot; * &quot; +\n\t\t b + &quot; = &quot; + result);\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic double div(double a, double b) {\n\t\tif (b == 0) {\n\t\t\tthrow new IllegalArgumentException(&quot;Division by zero&quot;);\n\t\t\t}\n\t\t\tdouble result = a \/ b;\n\t\t\tSystem.out.println(a + &quot; \/ &quot; + b + &quot; = &quot; + result);\n\t\t\treturn result;\n\t}\n\n}\n<\/pre><\/div>\n\n\n<p>And a Unit Calculator interface for convert the unit:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\npublic interface UnitCalculator {\n\n\tpublic double kilogramToPound(double kilogram);\n\tpublic double kilometerToMile(double kilometer);\n\n}\n<\/pre><\/div>\n\n\n<p>And implementation of this interface:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\nimport org.springframework.stereotype.Component;\n\n@Component(&quot;unitCalculator&quot;)\npublic class UnitCalculatorImpl implements UnitCalculator {\n\n\t@Override\n\tpublic double kilogramToPound(double kilogram) {\n\t\tdouble pound = kilogram * 2.2;\n\t\tSystem.out.println(kilogram + &quot; kilogram = &quot; + pound + &quot; pound&quot;);\n\t\treturn pound;\n\t}\n\n\t@Override\n\tpublic double kilometerToMile(double kilometer) {\n\t\tdouble mile = kilometer * 0.62;\n\t\tSystem.out.println(kilometer + &quot; kilometer = &quot; + mile + &quot; mile&quot;);\n\t\treturn mile;\n\t}\n\n}\n<\/pre><\/div>\n\n\n<p>For testing the aspects you need to have these dependencies:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: xml; title: ; notranslate\" title=\"\">\n&lt;dependency&gt;\n    \t&lt;groupId&gt;org.aspectj&lt;\/groupId&gt;\n    \t&lt;artifactId&gt;aspectjweaver&lt;\/artifactId&gt;\n    \t&lt;optional&gt;true&lt;\/optional&gt;\n&lt;\/dependency&gt;\n\t\t\n&lt;dependency&gt;\n    \t&lt;groupId&gt;org.aspectj&lt;\/groupId&gt;\n    \t&lt;artifactId&gt;aspectjrt&lt;\/artifactId&gt;\n    \t&lt;optional&gt;true&lt;\/optional&gt;\n&lt;\/dependency&gt;\n<\/pre><\/div>\n\n\n<p>The first we need to do in order to have an aspect is write that aspect:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\nimport java.util.Arrays;\n\nimport org.aspectj.lang.JoinPoint;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.aspectj.lang.annotation.Aspect;\nimport org.aspectj.lang.annotation.Before;\nimport org.springframework.stereotype.Component;\n\n@Aspect\n@Component\npublic class CalculatorLoggingAspect {\n\t\n\tprivate Log log = LogFactory.getLog(this.getClass());\n\t\n\t@Before(&quot;execution(* ArithmeticCalculator.add(..))&quot;)\n\tpublic void logBefore() {\n\t\tlog.info(&quot;The method add() begins.&quot;);\n\t}\n\n}\n<\/pre><\/div>\n\n\n<p>This pointcut expression:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n&quot;execution(* ArithmeticCalculator.add(..))&quot;\n<\/pre><\/div>\n\n\n<p>matches the <code>add()<\/code> method execution of the <code>ArithmeticCalculator<\/code> interface. The preceding wildcard in this expression matches any modifier (public, protected, and private) and any return type. The two dots in the argument list match any number of arguments.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><a href=\"https:\/\/aliyargunes.com.tr\/blog\/wp-content\/uploads\/2020\/09\/aspectj-pointcut-explanation.png\"><img loading=\"lazy\" decoding=\"async\" width=\"640\" height=\"212\" src=\"https:\/\/aliyargunes.com.tr\/blog\/wp-content\/uploads\/2020\/09\/aspectj-pointcut-explanation.png\" alt=\"\" class=\"wp-image-679\" srcset=\"https:\/\/aliyargunes.com.tr\/blog\/wp-content\/uploads\/2020\/09\/aspectj-pointcut-explanation.png 640w, https:\/\/aliyargunes.com.tr\/blog\/wp-content\/uploads\/2020\/09\/aspectj-pointcut-explanation-300x99.png 300w\" sizes=\"(max-width: 640px) 100vw, 640px\" \/><\/a><\/figure><\/div>\n\n\n\n<p>Next, create a Spring configuration to scan all POJOs, including the POJO calculator implementation and aspect and including the <code>@EnableAspectJAutoProxy<\/code> annotation. To enable annotation support in the Spring IoC container, you have to add <code>@EnableAspectJAutoProxy<\/code> to your configuration classes.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\nimport org.springframework.context.annotation.ComponentScan;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.EnableAspectJAutoProxy;\n\n@Configuration\n@EnableAspectJAutoProxy\n@ComponentScan\npublic class CalculatorConfiguration {\n\n}\n<\/pre><\/div>\n\n\n<p>Now we can test our first Aspect with this test class:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\nimport org.junit.jupiter.api.Test;\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.annotation.AnnotationConfigApplicationContext;\n\nclass AspectTest {\n\n\t@Test\n\tvoid test() {\n\t\tApplicationContext context = new AnnotationConfigApplicationContext(CalculatorConfiguration.class);\n\t\t\t\t\n\t\t\t\tArithmeticCalculator arithmeticCalculator =\n\t\t\t\tcontext.getBean(&quot;arithmeticCalculator&quot;, ArithmeticCalculator.class);\n\t\t\t\tarithmeticCalculator.add(1, 2);\n\t\t\t\tarithmeticCalculator.sub(4, 3);\n\t\t\t\tarithmeticCalculator.mul(2, 3);\n\t\t\t\tarithmeticCalculator.div(4, 2);\n\t\t\t\tUnitCalculator unitCalculator = context.getBean(&quot;unitCalculator&quot;, UnitCalculator.class);\n\t\t\t\tunitCalculator.kilogramToPound(10);\n\t\t\t\tunitCalculator.kilometerToMile(5);\n\t}\n\n}\n<\/pre><\/div>\n\n\n<p>And this is console output of our test:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nThe method add() begins.\n1.0 + 2.0 = 3.0\n4.0 - 3.0 = 1.0\n2.0 * 3.0 = 6.0\n4.0 \/ 2.0 = 2.0\n10.0 kilogram = 22.0 pound\n5.0 kilometer = 3.1 mile\n<\/pre><\/div>\n\n\n<p>If you want to use an advice that runs before every method you can add this advice to the aspect:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; title: ; notranslate\" title=\"\">\n@Before(&quot;execution(* *.*(..))&quot;)\n\tpublic void logBeforeAll(JoinPoint joinPoint) {\n\t\tlog.info(&quot;This is logBeforeAll! The method &quot; + joinPoint.getSignature().getName()\n\t\t\t\t+ &quot;() begins with &quot; + Arrays.toString(joinPoint.getArgs()));\n\t}\n<\/pre><\/div>\n\n\n<p>The execution points matched by a <strong>pointcut<\/strong> are called <strong>join points<\/strong> (in this case the <strong>pointcut<\/strong> is &#8220;<code>execution(* *<em>.<\/em>*(..))<\/code>&#8220;). In this term, a <strong>pointcut<\/strong> is an expression to match a set of <strong>join points<\/strong>, while an <strong>advice<\/strong> is the action to take at a particular <strong>join point<\/strong>.<br>For your advice to access the detail of the current join point, you can declare an argument of type <code>JoinPoint<\/code> in your advice method. Then, you can get access to join point details such as the method name and argument values. Now, you can expand your <strong>pointcut<\/strong> to match all methods by changing the class name and method name to wildcards.<\/p>\n\n\n\n<p>The output looks like this:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nThis is logBeforeAll! The method add() begins with &#x5B;1.0, 2.0] \n1.0 + 2.0 = 3.0\nThis is logBeforeAll! The method sub() begins with &#x5B;4.0, 3.0] \n4.0 - 3.0 = 1.0\nThis is logBeforeAll! The method mul() begins with &#x5B;2.0, 3.0]\n2.0 * 3.0 = 6.0\nThis is logBeforeAll! The method div() begins with &#x5B;4.0, 2.0]\n4.0 \/ 2.0 = 2.0\nThis is logBeforeAll! The method kilogramToPound() begins with &#x5B;10.0]\n10.0 kilogram = 22.0 pound\nThis is logBeforeAll! The method kilometerToMile() begins with &#x5B;5.0]\n5.0 kilometer = 3.1 mile\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">@After Advice<\/h2>\n\n\n\n<p>An after advice is executed after a join point finishes and is represented by a method annotated with @After, whenever it returns a result or throws an exception.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">@AfterReturning Advice<\/h2>\n\n\n\n<p>An after advice is executed regardless of whether a join point returns normally or throws an exception. If you would like to perform logging only when a join point returns, you should replace the after advice with an after returning advice.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">@AfterThrowing Advice<\/h2>\n\n\n\n<p>An after throwing advice is executed only when an exception is thrown by a join point.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">@Around Advice<\/h2>\n\n\n\n<p>It gains full control of a join point, so you can combine all the actions of the preceding advices into one single advice. You can even control when, and whether, to proceed with the original join point execution.<\/p>\n\n\n\n<p><strong>A common rule for choosing an advice type is to use the least powerful one that can satisfy your requirements.<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>An aspect is a Java class that modularizes a set of concerns (e.g., logging or transaction management) that cuts across multiple types and objects. Java classes that modularize such concerns are decorated with the @Aspect annotation. In AOP terminology, aspects &hellip; <a href=\"https:\/\/aliyargunes.com.tr\/blog\/aspect-oriented-programming-notes-2-setting-up-aop-dependencies-and-declaring-aspects-advices-pointcuts\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":675,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[94,8],"tags":[101,103,104,105,102,98,97,100,99,96],"class_list":["post-632","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-spring-framework","category-works","tag-after","tag-afterreturning","tag-afterthrowing","tag-around","tag-before","tag-advice","tag-aspect-oriented-programming","tag-join-points","tag-pointcuts","tag-spring-framework"],"_links":{"self":[{"href":"https:\/\/aliyargunes.com.tr\/blog\/wp-json\/wp\/v2\/posts\/632"}],"collection":[{"href":"https:\/\/aliyargunes.com.tr\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/aliyargunes.com.tr\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/aliyargunes.com.tr\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/aliyargunes.com.tr\/blog\/wp-json\/wp\/v2\/comments?post=632"}],"version-history":[{"count":44,"href":"https:\/\/aliyargunes.com.tr\/blog\/wp-json\/wp\/v2\/posts\/632\/revisions"}],"predecessor-version":[{"id":681,"href":"https:\/\/aliyargunes.com.tr\/blog\/wp-json\/wp\/v2\/posts\/632\/revisions\/681"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/aliyargunes.com.tr\/blog\/wp-json\/wp\/v2\/media\/675"}],"wp:attachment":[{"href":"https:\/\/aliyargunes.com.tr\/blog\/wp-json\/wp\/v2\/media?parent=632"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/aliyargunes.com.tr\/blog\/wp-json\/wp\/v2\/categories?post=632"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/aliyargunes.com.tr\/blog\/wp-json\/wp\/v2\/tags?post=632"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}