How to code a Pointcut and bind arguments in Spring AOP?












1















I store an account Object in session when a user logging in. Now I want to realize that I would check if any account exists in session when each request proceeding. So I come up with using Spring AOP. Now test binding methods in Controllers:



@Aspect
public class AuthAspect {
@Pointcut("execution(* com.bolaa.sentiment.controller..*.*(javax.servlet.http.HttpSession,..)) && args" +
"(session,args)")
public void around(HttpSession session, Object ... args) {
}

@Around("around(session,args)")
public void checkLoggedIn(ProceedingJoinPoint pjp, HttpSession session, Object ... args) {
System.out.println("Aspect start");
try {
pjp.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
System.out.println("Aspect end");
}
}


For example, a request as follows:



@RestController
@RequestMapping("/role")
public class RoleController {
@Autowired
public IRoleService iRoleService;

@RequestMapping(value = "getRoles")
public IPage<Role> getRoles(HttpSession session, Integer pageNum, Integer pageSize) {
return iRoleService.selectListPage(pageNum, pageSize);
}
}


When I get the Roles, there isn't any logs in console. It couldn't bind the method getRoles(session,..). How to correct the Pointcut by arguments with HttpSession first and omit the rest of the arguments?










share|improve this question



























    1















    I store an account Object in session when a user logging in. Now I want to realize that I would check if any account exists in session when each request proceeding. So I come up with using Spring AOP. Now test binding methods in Controllers:



    @Aspect
    public class AuthAspect {
    @Pointcut("execution(* com.bolaa.sentiment.controller..*.*(javax.servlet.http.HttpSession,..)) && args" +
    "(session,args)")
    public void around(HttpSession session, Object ... args) {
    }

    @Around("around(session,args)")
    public void checkLoggedIn(ProceedingJoinPoint pjp, HttpSession session, Object ... args) {
    System.out.println("Aspect start");
    try {
    pjp.proceed();
    } catch (Throwable throwable) {
    throwable.printStackTrace();
    }
    System.out.println("Aspect end");
    }
    }


    For example, a request as follows:



    @RestController
    @RequestMapping("/role")
    public class RoleController {
    @Autowired
    public IRoleService iRoleService;

    @RequestMapping(value = "getRoles")
    public IPage<Role> getRoles(HttpSession session, Integer pageNum, Integer pageSize) {
    return iRoleService.selectListPage(pageNum, pageSize);
    }
    }


    When I get the Roles, there isn't any logs in console. It couldn't bind the method getRoles(session,..). How to correct the Pointcut by arguments with HttpSession first and omit the rest of the arguments?










    share|improve this question

























      1












      1








      1








      I store an account Object in session when a user logging in. Now I want to realize that I would check if any account exists in session when each request proceeding. So I come up with using Spring AOP. Now test binding methods in Controllers:



      @Aspect
      public class AuthAspect {
      @Pointcut("execution(* com.bolaa.sentiment.controller..*.*(javax.servlet.http.HttpSession,..)) && args" +
      "(session,args)")
      public void around(HttpSession session, Object ... args) {
      }

      @Around("around(session,args)")
      public void checkLoggedIn(ProceedingJoinPoint pjp, HttpSession session, Object ... args) {
      System.out.println("Aspect start");
      try {
      pjp.proceed();
      } catch (Throwable throwable) {
      throwable.printStackTrace();
      }
      System.out.println("Aspect end");
      }
      }


      For example, a request as follows:



      @RestController
      @RequestMapping("/role")
      public class RoleController {
      @Autowired
      public IRoleService iRoleService;

      @RequestMapping(value = "getRoles")
      public IPage<Role> getRoles(HttpSession session, Integer pageNum, Integer pageSize) {
      return iRoleService.selectListPage(pageNum, pageSize);
      }
      }


      When I get the Roles, there isn't any logs in console. It couldn't bind the method getRoles(session,..). How to correct the Pointcut by arguments with HttpSession first and omit the rest of the arguments?










      share|improve this question














      I store an account Object in session when a user logging in. Now I want to realize that I would check if any account exists in session when each request proceeding. So I come up with using Spring AOP. Now test binding methods in Controllers:



      @Aspect
      public class AuthAspect {
      @Pointcut("execution(* com.bolaa.sentiment.controller..*.*(javax.servlet.http.HttpSession,..)) && args" +
      "(session,args)")
      public void around(HttpSession session, Object ... args) {
      }

      @Around("around(session,args)")
      public void checkLoggedIn(ProceedingJoinPoint pjp, HttpSession session, Object ... args) {
      System.out.println("Aspect start");
      try {
      pjp.proceed();
      } catch (Throwable throwable) {
      throwable.printStackTrace();
      }
      System.out.println("Aspect end");
      }
      }


      For example, a request as follows:



      @RestController
      @RequestMapping("/role")
      public class RoleController {
      @Autowired
      public IRoleService iRoleService;

      @RequestMapping(value = "getRoles")
      public IPage<Role> getRoles(HttpSession session, Integer pageNum, Integer pageSize) {
      return iRoleService.selectListPage(pageNum, pageSize);
      }
      }


      When I get the Roles, there isn't any logs in console. It couldn't bind the method getRoles(session,..). How to correct the Pointcut by arguments with HttpSession first and omit the rest of the arguments?







      spring spring-boot aop






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 26 '18 at 3:54









      Saeron MengSaeron Meng

      8211




      8211
























          2 Answers
          2






          active

          oldest

          votes


















          1














          Arguments matching is strict and bit complex - () matches a method that takes no parameters, whereas (..) matches any number (zero or more) of parameters. The (*) pattern matches a method that takes one parameter of any type.



          But args limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types.



          when specifying args need to specify all the arguments as that will be used to match correct method.



          So change your pointcut as below -



          @Pointcut("execution(* com.bolaa.sentiment.controller..*.*(..)) && args(session,pageNum, pageSize)")





          share|improve this answer
























          • This answer is incorrect, sorry. See my own one for the correct answer.

            – kriegaex
            Dec 11 '18 at 6:50



















          0














          First a few general remarks about your aspect code:




          • An around advice needs to return something, if the intercepted method is not void, so the return type should be Object or something more specific. Otherwise the pointcut will not match.


          • You should never just swallow exceptions or only log them, but actually re-throw them after logging, unless you handle them correctly and return a valid object or null.


          • A method signature in AspectJ syntax like foo.bar..*.*(..) is a bit too verbose and can be abbreviated like foo.bar..*(..).


          • The assumption that ignored arguments could be collected in an additional ... parameter and magically end up in an array is wrong. If you want to ignore something you can just use jokers like '*' or '..' instead, but not bind the ignored arguments to pointcut parameters.


          • The assumption that you have to specify and bind all parameters, as shown by Amit Naik, is also wrong. You can do that, but do not have to.



          So here is your solution:



          package de.scrum_master.aspect;

          import javax.servlet.http.HttpSession;

          import org.aspectj.lang.ProceedingJoinPoint;
          import org.aspectj.lang.annotation.Around;
          import org.aspectj.lang.annotation.Aspect;
          import org.aspectj.lang.annotation.Pointcut;

          @Aspect
          public class AuthAspect {
          @Pointcut("execution(* com.bolaa.sentiment.controller..*(..)) && args(session, ..)")
          public void myPointcut(HttpSession session) {}

          @Around("myPointcut(session)")
          public Object checkLoggedIn(ProceedingJoinPoint pjp, HttpSession session) throws Throwable {
          System.out.println("[START] " + pjp + " -> " + session);
          try {
          return pjp.proceed();
          }
          catch (Throwable throwable) {
          throwable.printStackTrace();
          throw throwable;
          }
          finally {
          System.out.println("[EXIT] " + pjp + " -> " + session);
          }
          }
          }


          This prints something like the following on the console:



          [START] execution(List com.bolaa.sentiment.controller.role.RoleController.getRoles(HttpSession, Integer, Integer)) -> com.bolaa.sentiment.controller.role.RoleController$1@7daf6ecc
          [EXIT] execution(List com.bolaa.sentiment.controller.role.RoleController.getRoles(HttpSession, Integer, Integer)) -> com.bolaa.sentiment.controller.role.RoleController$1@7daf6ecc





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53474592%2fhow-to-code-a-pointcut-and-bind-arguments-in-spring-aop%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            Arguments matching is strict and bit complex - () matches a method that takes no parameters, whereas (..) matches any number (zero or more) of parameters. The (*) pattern matches a method that takes one parameter of any type.



            But args limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types.



            when specifying args need to specify all the arguments as that will be used to match correct method.



            So change your pointcut as below -



            @Pointcut("execution(* com.bolaa.sentiment.controller..*.*(..)) && args(session,pageNum, pageSize)")





            share|improve this answer
























            • This answer is incorrect, sorry. See my own one for the correct answer.

              – kriegaex
              Dec 11 '18 at 6:50
















            1














            Arguments matching is strict and bit complex - () matches a method that takes no parameters, whereas (..) matches any number (zero or more) of parameters. The (*) pattern matches a method that takes one parameter of any type.



            But args limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types.



            when specifying args need to specify all the arguments as that will be used to match correct method.



            So change your pointcut as below -



            @Pointcut("execution(* com.bolaa.sentiment.controller..*.*(..)) && args(session,pageNum, pageSize)")





            share|improve this answer
























            • This answer is incorrect, sorry. See my own one for the correct answer.

              – kriegaex
              Dec 11 '18 at 6:50














            1












            1








            1







            Arguments matching is strict and bit complex - () matches a method that takes no parameters, whereas (..) matches any number (zero or more) of parameters. The (*) pattern matches a method that takes one parameter of any type.



            But args limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types.



            when specifying args need to specify all the arguments as that will be used to match correct method.



            So change your pointcut as below -



            @Pointcut("execution(* com.bolaa.sentiment.controller..*.*(..)) && args(session,pageNum, pageSize)")





            share|improve this answer













            Arguments matching is strict and bit complex - () matches a method that takes no parameters, whereas (..) matches any number (zero or more) of parameters. The (*) pattern matches a method that takes one parameter of any type.



            But args limits matching to join points (the execution of methods when using Spring AOP) where the arguments are instances of the given types.



            when specifying args need to specify all the arguments as that will be used to match correct method.



            So change your pointcut as below -



            @Pointcut("execution(* com.bolaa.sentiment.controller..*.*(..)) && args(session,pageNum, pageSize)")






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 26 '18 at 6:39









            Amit NaikAmit Naik

            18410




            18410













            • This answer is incorrect, sorry. See my own one for the correct answer.

              – kriegaex
              Dec 11 '18 at 6:50



















            • This answer is incorrect, sorry. See my own one for the correct answer.

              – kriegaex
              Dec 11 '18 at 6:50

















            This answer is incorrect, sorry. See my own one for the correct answer.

            – kriegaex
            Dec 11 '18 at 6:50





            This answer is incorrect, sorry. See my own one for the correct answer.

            – kriegaex
            Dec 11 '18 at 6:50













            0














            First a few general remarks about your aspect code:




            • An around advice needs to return something, if the intercepted method is not void, so the return type should be Object or something more specific. Otherwise the pointcut will not match.


            • You should never just swallow exceptions or only log them, but actually re-throw them after logging, unless you handle them correctly and return a valid object or null.


            • A method signature in AspectJ syntax like foo.bar..*.*(..) is a bit too verbose and can be abbreviated like foo.bar..*(..).


            • The assumption that ignored arguments could be collected in an additional ... parameter and magically end up in an array is wrong. If you want to ignore something you can just use jokers like '*' or '..' instead, but not bind the ignored arguments to pointcut parameters.


            • The assumption that you have to specify and bind all parameters, as shown by Amit Naik, is also wrong. You can do that, but do not have to.



            So here is your solution:



            package de.scrum_master.aspect;

            import javax.servlet.http.HttpSession;

            import org.aspectj.lang.ProceedingJoinPoint;
            import org.aspectj.lang.annotation.Around;
            import org.aspectj.lang.annotation.Aspect;
            import org.aspectj.lang.annotation.Pointcut;

            @Aspect
            public class AuthAspect {
            @Pointcut("execution(* com.bolaa.sentiment.controller..*(..)) && args(session, ..)")
            public void myPointcut(HttpSession session) {}

            @Around("myPointcut(session)")
            public Object checkLoggedIn(ProceedingJoinPoint pjp, HttpSession session) throws Throwable {
            System.out.println("[START] " + pjp + " -> " + session);
            try {
            return pjp.proceed();
            }
            catch (Throwable throwable) {
            throwable.printStackTrace();
            throw throwable;
            }
            finally {
            System.out.println("[EXIT] " + pjp + " -> " + session);
            }
            }
            }


            This prints something like the following on the console:



            [START] execution(List com.bolaa.sentiment.controller.role.RoleController.getRoles(HttpSession, Integer, Integer)) -> com.bolaa.sentiment.controller.role.RoleController$1@7daf6ecc
            [EXIT] execution(List com.bolaa.sentiment.controller.role.RoleController.getRoles(HttpSession, Integer, Integer)) -> com.bolaa.sentiment.controller.role.RoleController$1@7daf6ecc





            share|improve this answer




























              0














              First a few general remarks about your aspect code:




              • An around advice needs to return something, if the intercepted method is not void, so the return type should be Object or something more specific. Otherwise the pointcut will not match.


              • You should never just swallow exceptions or only log them, but actually re-throw them after logging, unless you handle them correctly and return a valid object or null.


              • A method signature in AspectJ syntax like foo.bar..*.*(..) is a bit too verbose and can be abbreviated like foo.bar..*(..).


              • The assumption that ignored arguments could be collected in an additional ... parameter and magically end up in an array is wrong. If you want to ignore something you can just use jokers like '*' or '..' instead, but not bind the ignored arguments to pointcut parameters.


              • The assumption that you have to specify and bind all parameters, as shown by Amit Naik, is also wrong. You can do that, but do not have to.



              So here is your solution:



              package de.scrum_master.aspect;

              import javax.servlet.http.HttpSession;

              import org.aspectj.lang.ProceedingJoinPoint;
              import org.aspectj.lang.annotation.Around;
              import org.aspectj.lang.annotation.Aspect;
              import org.aspectj.lang.annotation.Pointcut;

              @Aspect
              public class AuthAspect {
              @Pointcut("execution(* com.bolaa.sentiment.controller..*(..)) && args(session, ..)")
              public void myPointcut(HttpSession session) {}

              @Around("myPointcut(session)")
              public Object checkLoggedIn(ProceedingJoinPoint pjp, HttpSession session) throws Throwable {
              System.out.println("[START] " + pjp + " -> " + session);
              try {
              return pjp.proceed();
              }
              catch (Throwable throwable) {
              throwable.printStackTrace();
              throw throwable;
              }
              finally {
              System.out.println("[EXIT] " + pjp + " -> " + session);
              }
              }
              }


              This prints something like the following on the console:



              [START] execution(List com.bolaa.sentiment.controller.role.RoleController.getRoles(HttpSession, Integer, Integer)) -> com.bolaa.sentiment.controller.role.RoleController$1@7daf6ecc
              [EXIT] execution(List com.bolaa.sentiment.controller.role.RoleController.getRoles(HttpSession, Integer, Integer)) -> com.bolaa.sentiment.controller.role.RoleController$1@7daf6ecc





              share|improve this answer


























                0












                0








                0







                First a few general remarks about your aspect code:




                • An around advice needs to return something, if the intercepted method is not void, so the return type should be Object or something more specific. Otherwise the pointcut will not match.


                • You should never just swallow exceptions or only log them, but actually re-throw them after logging, unless you handle them correctly and return a valid object or null.


                • A method signature in AspectJ syntax like foo.bar..*.*(..) is a bit too verbose and can be abbreviated like foo.bar..*(..).


                • The assumption that ignored arguments could be collected in an additional ... parameter and magically end up in an array is wrong. If you want to ignore something you can just use jokers like '*' or '..' instead, but not bind the ignored arguments to pointcut parameters.


                • The assumption that you have to specify and bind all parameters, as shown by Amit Naik, is also wrong. You can do that, but do not have to.



                So here is your solution:



                package de.scrum_master.aspect;

                import javax.servlet.http.HttpSession;

                import org.aspectj.lang.ProceedingJoinPoint;
                import org.aspectj.lang.annotation.Around;
                import org.aspectj.lang.annotation.Aspect;
                import org.aspectj.lang.annotation.Pointcut;

                @Aspect
                public class AuthAspect {
                @Pointcut("execution(* com.bolaa.sentiment.controller..*(..)) && args(session, ..)")
                public void myPointcut(HttpSession session) {}

                @Around("myPointcut(session)")
                public Object checkLoggedIn(ProceedingJoinPoint pjp, HttpSession session) throws Throwable {
                System.out.println("[START] " + pjp + " -> " + session);
                try {
                return pjp.proceed();
                }
                catch (Throwable throwable) {
                throwable.printStackTrace();
                throw throwable;
                }
                finally {
                System.out.println("[EXIT] " + pjp + " -> " + session);
                }
                }
                }


                This prints something like the following on the console:



                [START] execution(List com.bolaa.sentiment.controller.role.RoleController.getRoles(HttpSession, Integer, Integer)) -> com.bolaa.sentiment.controller.role.RoleController$1@7daf6ecc
                [EXIT] execution(List com.bolaa.sentiment.controller.role.RoleController.getRoles(HttpSession, Integer, Integer)) -> com.bolaa.sentiment.controller.role.RoleController$1@7daf6ecc





                share|improve this answer













                First a few general remarks about your aspect code:




                • An around advice needs to return something, if the intercepted method is not void, so the return type should be Object or something more specific. Otherwise the pointcut will not match.


                • You should never just swallow exceptions or only log them, but actually re-throw them after logging, unless you handle them correctly and return a valid object or null.


                • A method signature in AspectJ syntax like foo.bar..*.*(..) is a bit too verbose and can be abbreviated like foo.bar..*(..).


                • The assumption that ignored arguments could be collected in an additional ... parameter and magically end up in an array is wrong. If you want to ignore something you can just use jokers like '*' or '..' instead, but not bind the ignored arguments to pointcut parameters.


                • The assumption that you have to specify and bind all parameters, as shown by Amit Naik, is also wrong. You can do that, but do not have to.



                So here is your solution:



                package de.scrum_master.aspect;

                import javax.servlet.http.HttpSession;

                import org.aspectj.lang.ProceedingJoinPoint;
                import org.aspectj.lang.annotation.Around;
                import org.aspectj.lang.annotation.Aspect;
                import org.aspectj.lang.annotation.Pointcut;

                @Aspect
                public class AuthAspect {
                @Pointcut("execution(* com.bolaa.sentiment.controller..*(..)) && args(session, ..)")
                public void myPointcut(HttpSession session) {}

                @Around("myPointcut(session)")
                public Object checkLoggedIn(ProceedingJoinPoint pjp, HttpSession session) throws Throwable {
                System.out.println("[START] " + pjp + " -> " + session);
                try {
                return pjp.proceed();
                }
                catch (Throwable throwable) {
                throwable.printStackTrace();
                throw throwable;
                }
                finally {
                System.out.println("[EXIT] " + pjp + " -> " + session);
                }
                }
                }


                This prints something like the following on the console:



                [START] execution(List com.bolaa.sentiment.controller.role.RoleController.getRoles(HttpSession, Integer, Integer)) -> com.bolaa.sentiment.controller.role.RoleController$1@7daf6ecc
                [EXIT] execution(List com.bolaa.sentiment.controller.role.RoleController.getRoles(HttpSession, Integer, Integer)) -> com.bolaa.sentiment.controller.role.RoleController$1@7daf6ecc






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Dec 11 '18 at 6:58









                kriegaexkriegaex

                32k366102




                32k366102






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53474592%2fhow-to-code-a-pointcut-and-bind-arguments-in-spring-aop%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Costa Masnaga

                    Fotorealismo

                    Sidney Franklin