Where to write Common code in spring boot











up vote
0
down vote

favorite












I want to write common code which should be execute before every method,
Where can I place this code in spring.



Thanks in advance.










share|improve this question


























    up vote
    0
    down vote

    favorite












    I want to write common code which should be execute before every method,
    Where can I place this code in spring.



    Thanks in advance.










    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I want to write common code which should be execute before every method,
      Where can I place this code in spring.



      Thanks in advance.










      share|improve this question













      I want to write common code which should be execute before every method,
      Where can I place this code in spring.



      Thanks in advance.







      spring spring-mvc spring-boot






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 21 hours ago









      Shiva

      74




      74
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          0
          down vote













          You should have a look at Spring AOP. With Spring AOP you can write Aspects which can be common code which is executed before/after a method. The following example is a simple Aspect:



          @Aspect
          public class EmployeeAspect {

          @Before("execution(public String getName())")
          public void getNameAdvice(){
          System.out.println("Executing Advice on getName()");
          }

          @Before("execution(* your.package.name.*.get*())")
          public void getAllAdvice(){
          System.out.println("Service method getter called");
          }
          }


          Within the @Before() annotation you can specify the exact method which is surrounded with the Aspect or you use the wildcard * to specify more methods. For this, you should be familiar with Pointcut expressions.






          share|improve this answer




























            up vote
            0
            down vote













            What you ask is not trivial but Aspect Oriented Programming (AoP) is one way to achieve that. This description assumes that you are somewhat familiar with the Proxy class, the InvocationHandler interface and the Interceptor pattern in general. As I said, not a totally trivial matter.





            1. Define the logic that you what to be executed before every method, or some method or whatever. Usually it is come kind of Interceptor, this is an example:



              public class TimeProfilerInterceptor implements MethodInterceptor {

              @Getter
              private final TimeStatistics statistics = new TimeStatistics();

              @Override
              public Object invoke(MethodInvocation invocation) throws Throwable {
              StopWatch watch = new StopWatch();
              try {
              watch.start();
              Object returnValue = invocation.proceed();
              return returnValue;
              }
              finally {
              // etc...
              }
              }
              }



            2. Define a place where your logic is wired to your methods. In this example, the place is a Spring component that extends AbstractBeanFactoryAwareAdvisingPostProcessor and implements InitializingBean. The afterPropertiesSet method is called by Spring once the initialization of the bean is done. The method uses the Advice class from spring-aop to identify the pointcuts i.e. the methods that must be wrapped by the interceptor. In this case, it is an annotation based pointcut, meaning that it matches every method that has a certain custom annotation on it (TimeProfiled).



              @Component
              public class TimeProfiledAnnotationPostProcessor
              extends AbstractBeanFactoryAwareAdvisingPostProcessor
              implements InitializingBean {

              @Autowired
              TimeProfilerInterceptor timeProfilerInterceptor;

              @Override
              public void afterPropertiesSet() throws Exception {
              this.setProxyTargetClass(true);
              Advice advice = timeProfilerInterceptor;
              Pointcut pointcut = new AnnotationMatchingPointcut(null, TimeProfiled.class);
              this.advisor = new DefaultPointcutAdvisor(pointcut, advice);
              }
              }



            3. Define your custom annotation to use where needed.



              @Target(ElementType.METHOD)
              @Retention(RetentionPolicy.RUNTIME)
              public @interface TimeProfiled {

              }



            4. Tell Spring to initiate the wrapping mechanism at startup via the following annotation upon a Spring Configuration or a SpringBootApplication:



              @ComponentScan(basePackageClasses = TimeProfiledAnnotationPostProcessor.class)
              @EnableAspectJAutoProxy(proxyTargetClass = true)



            You can change the pointcut so that it matches other methods with other criteria, there is an entire syntax to do that, a world in itself, this is just a small example...






            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',
              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%2f53265930%2fwhere-to-write-common-code-in-spring-boot%23new-answer', 'question_page');
              }
              );

              Post as a guest
































              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              0
              down vote













              You should have a look at Spring AOP. With Spring AOP you can write Aspects which can be common code which is executed before/after a method. The following example is a simple Aspect:



              @Aspect
              public class EmployeeAspect {

              @Before("execution(public String getName())")
              public void getNameAdvice(){
              System.out.println("Executing Advice on getName()");
              }

              @Before("execution(* your.package.name.*.get*())")
              public void getAllAdvice(){
              System.out.println("Service method getter called");
              }
              }


              Within the @Before() annotation you can specify the exact method which is surrounded with the Aspect or you use the wildcard * to specify more methods. For this, you should be familiar with Pointcut expressions.






              share|improve this answer

























                up vote
                0
                down vote













                You should have a look at Spring AOP. With Spring AOP you can write Aspects which can be common code which is executed before/after a method. The following example is a simple Aspect:



                @Aspect
                public class EmployeeAspect {

                @Before("execution(public String getName())")
                public void getNameAdvice(){
                System.out.println("Executing Advice on getName()");
                }

                @Before("execution(* your.package.name.*.get*())")
                public void getAllAdvice(){
                System.out.println("Service method getter called");
                }
                }


                Within the @Before() annotation you can specify the exact method which is surrounded with the Aspect or you use the wildcard * to specify more methods. For this, you should be familiar with Pointcut expressions.






                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  You should have a look at Spring AOP. With Spring AOP you can write Aspects which can be common code which is executed before/after a method. The following example is a simple Aspect:



                  @Aspect
                  public class EmployeeAspect {

                  @Before("execution(public String getName())")
                  public void getNameAdvice(){
                  System.out.println("Executing Advice on getName()");
                  }

                  @Before("execution(* your.package.name.*.get*())")
                  public void getAllAdvice(){
                  System.out.println("Service method getter called");
                  }
                  }


                  Within the @Before() annotation you can specify the exact method which is surrounded with the Aspect or you use the wildcard * to specify more methods. For this, you should be familiar with Pointcut expressions.






                  share|improve this answer












                  You should have a look at Spring AOP. With Spring AOP you can write Aspects which can be common code which is executed before/after a method. The following example is a simple Aspect:



                  @Aspect
                  public class EmployeeAspect {

                  @Before("execution(public String getName())")
                  public void getNameAdvice(){
                  System.out.println("Executing Advice on getName()");
                  }

                  @Before("execution(* your.package.name.*.get*())")
                  public void getAllAdvice(){
                  System.out.println("Service method getter called");
                  }
                  }


                  Within the @Before() annotation you can specify the exact method which is surrounded with the Aspect or you use the wildcard * to specify more methods. For this, you should be familiar with Pointcut expressions.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 20 hours ago









                  rieckpil

                  1,0621516




                  1,0621516
























                      up vote
                      0
                      down vote













                      What you ask is not trivial but Aspect Oriented Programming (AoP) is one way to achieve that. This description assumes that you are somewhat familiar with the Proxy class, the InvocationHandler interface and the Interceptor pattern in general. As I said, not a totally trivial matter.





                      1. Define the logic that you what to be executed before every method, or some method or whatever. Usually it is come kind of Interceptor, this is an example:



                        public class TimeProfilerInterceptor implements MethodInterceptor {

                        @Getter
                        private final TimeStatistics statistics = new TimeStatistics();

                        @Override
                        public Object invoke(MethodInvocation invocation) throws Throwable {
                        StopWatch watch = new StopWatch();
                        try {
                        watch.start();
                        Object returnValue = invocation.proceed();
                        return returnValue;
                        }
                        finally {
                        // etc...
                        }
                        }
                        }



                      2. Define a place where your logic is wired to your methods. In this example, the place is a Spring component that extends AbstractBeanFactoryAwareAdvisingPostProcessor and implements InitializingBean. The afterPropertiesSet method is called by Spring once the initialization of the bean is done. The method uses the Advice class from spring-aop to identify the pointcuts i.e. the methods that must be wrapped by the interceptor. In this case, it is an annotation based pointcut, meaning that it matches every method that has a certain custom annotation on it (TimeProfiled).



                        @Component
                        public class TimeProfiledAnnotationPostProcessor
                        extends AbstractBeanFactoryAwareAdvisingPostProcessor
                        implements InitializingBean {

                        @Autowired
                        TimeProfilerInterceptor timeProfilerInterceptor;

                        @Override
                        public void afterPropertiesSet() throws Exception {
                        this.setProxyTargetClass(true);
                        Advice advice = timeProfilerInterceptor;
                        Pointcut pointcut = new AnnotationMatchingPointcut(null, TimeProfiled.class);
                        this.advisor = new DefaultPointcutAdvisor(pointcut, advice);
                        }
                        }



                      3. Define your custom annotation to use where needed.



                        @Target(ElementType.METHOD)
                        @Retention(RetentionPolicy.RUNTIME)
                        public @interface TimeProfiled {

                        }



                      4. Tell Spring to initiate the wrapping mechanism at startup via the following annotation upon a Spring Configuration or a SpringBootApplication:



                        @ComponentScan(basePackageClasses = TimeProfiledAnnotationPostProcessor.class)
                        @EnableAspectJAutoProxy(proxyTargetClass = true)



                      You can change the pointcut so that it matches other methods with other criteria, there is an entire syntax to do that, a world in itself, this is just a small example...






                      share|improve this answer



























                        up vote
                        0
                        down vote













                        What you ask is not trivial but Aspect Oriented Programming (AoP) is one way to achieve that. This description assumes that you are somewhat familiar with the Proxy class, the InvocationHandler interface and the Interceptor pattern in general. As I said, not a totally trivial matter.





                        1. Define the logic that you what to be executed before every method, or some method or whatever. Usually it is come kind of Interceptor, this is an example:



                          public class TimeProfilerInterceptor implements MethodInterceptor {

                          @Getter
                          private final TimeStatistics statistics = new TimeStatistics();

                          @Override
                          public Object invoke(MethodInvocation invocation) throws Throwable {
                          StopWatch watch = new StopWatch();
                          try {
                          watch.start();
                          Object returnValue = invocation.proceed();
                          return returnValue;
                          }
                          finally {
                          // etc...
                          }
                          }
                          }



                        2. Define a place where your logic is wired to your methods. In this example, the place is a Spring component that extends AbstractBeanFactoryAwareAdvisingPostProcessor and implements InitializingBean. The afterPropertiesSet method is called by Spring once the initialization of the bean is done. The method uses the Advice class from spring-aop to identify the pointcuts i.e. the methods that must be wrapped by the interceptor. In this case, it is an annotation based pointcut, meaning that it matches every method that has a certain custom annotation on it (TimeProfiled).



                          @Component
                          public class TimeProfiledAnnotationPostProcessor
                          extends AbstractBeanFactoryAwareAdvisingPostProcessor
                          implements InitializingBean {

                          @Autowired
                          TimeProfilerInterceptor timeProfilerInterceptor;

                          @Override
                          public void afterPropertiesSet() throws Exception {
                          this.setProxyTargetClass(true);
                          Advice advice = timeProfilerInterceptor;
                          Pointcut pointcut = new AnnotationMatchingPointcut(null, TimeProfiled.class);
                          this.advisor = new DefaultPointcutAdvisor(pointcut, advice);
                          }
                          }



                        3. Define your custom annotation to use where needed.



                          @Target(ElementType.METHOD)
                          @Retention(RetentionPolicy.RUNTIME)
                          public @interface TimeProfiled {

                          }



                        4. Tell Spring to initiate the wrapping mechanism at startup via the following annotation upon a Spring Configuration or a SpringBootApplication:



                          @ComponentScan(basePackageClasses = TimeProfiledAnnotationPostProcessor.class)
                          @EnableAspectJAutoProxy(proxyTargetClass = true)



                        You can change the pointcut so that it matches other methods with other criteria, there is an entire syntax to do that, a world in itself, this is just a small example...






                        share|improve this answer

























                          up vote
                          0
                          down vote










                          up vote
                          0
                          down vote









                          What you ask is not trivial but Aspect Oriented Programming (AoP) is one way to achieve that. This description assumes that you are somewhat familiar with the Proxy class, the InvocationHandler interface and the Interceptor pattern in general. As I said, not a totally trivial matter.





                          1. Define the logic that you what to be executed before every method, or some method or whatever. Usually it is come kind of Interceptor, this is an example:



                            public class TimeProfilerInterceptor implements MethodInterceptor {

                            @Getter
                            private final TimeStatistics statistics = new TimeStatistics();

                            @Override
                            public Object invoke(MethodInvocation invocation) throws Throwable {
                            StopWatch watch = new StopWatch();
                            try {
                            watch.start();
                            Object returnValue = invocation.proceed();
                            return returnValue;
                            }
                            finally {
                            // etc...
                            }
                            }
                            }



                          2. Define a place where your logic is wired to your methods. In this example, the place is a Spring component that extends AbstractBeanFactoryAwareAdvisingPostProcessor and implements InitializingBean. The afterPropertiesSet method is called by Spring once the initialization of the bean is done. The method uses the Advice class from spring-aop to identify the pointcuts i.e. the methods that must be wrapped by the interceptor. In this case, it is an annotation based pointcut, meaning that it matches every method that has a certain custom annotation on it (TimeProfiled).



                            @Component
                            public class TimeProfiledAnnotationPostProcessor
                            extends AbstractBeanFactoryAwareAdvisingPostProcessor
                            implements InitializingBean {

                            @Autowired
                            TimeProfilerInterceptor timeProfilerInterceptor;

                            @Override
                            public void afterPropertiesSet() throws Exception {
                            this.setProxyTargetClass(true);
                            Advice advice = timeProfilerInterceptor;
                            Pointcut pointcut = new AnnotationMatchingPointcut(null, TimeProfiled.class);
                            this.advisor = new DefaultPointcutAdvisor(pointcut, advice);
                            }
                            }



                          3. Define your custom annotation to use where needed.



                            @Target(ElementType.METHOD)
                            @Retention(RetentionPolicy.RUNTIME)
                            public @interface TimeProfiled {

                            }



                          4. Tell Spring to initiate the wrapping mechanism at startup via the following annotation upon a Spring Configuration or a SpringBootApplication:



                            @ComponentScan(basePackageClasses = TimeProfiledAnnotationPostProcessor.class)
                            @EnableAspectJAutoProxy(proxyTargetClass = true)



                          You can change the pointcut so that it matches other methods with other criteria, there is an entire syntax to do that, a world in itself, this is just a small example...






                          share|improve this answer














                          What you ask is not trivial but Aspect Oriented Programming (AoP) is one way to achieve that. This description assumes that you are somewhat familiar with the Proxy class, the InvocationHandler interface and the Interceptor pattern in general. As I said, not a totally trivial matter.





                          1. Define the logic that you what to be executed before every method, or some method or whatever. Usually it is come kind of Interceptor, this is an example:



                            public class TimeProfilerInterceptor implements MethodInterceptor {

                            @Getter
                            private final TimeStatistics statistics = new TimeStatistics();

                            @Override
                            public Object invoke(MethodInvocation invocation) throws Throwable {
                            StopWatch watch = new StopWatch();
                            try {
                            watch.start();
                            Object returnValue = invocation.proceed();
                            return returnValue;
                            }
                            finally {
                            // etc...
                            }
                            }
                            }



                          2. Define a place where your logic is wired to your methods. In this example, the place is a Spring component that extends AbstractBeanFactoryAwareAdvisingPostProcessor and implements InitializingBean. The afterPropertiesSet method is called by Spring once the initialization of the bean is done. The method uses the Advice class from spring-aop to identify the pointcuts i.e. the methods that must be wrapped by the interceptor. In this case, it is an annotation based pointcut, meaning that it matches every method that has a certain custom annotation on it (TimeProfiled).



                            @Component
                            public class TimeProfiledAnnotationPostProcessor
                            extends AbstractBeanFactoryAwareAdvisingPostProcessor
                            implements InitializingBean {

                            @Autowired
                            TimeProfilerInterceptor timeProfilerInterceptor;

                            @Override
                            public void afterPropertiesSet() throws Exception {
                            this.setProxyTargetClass(true);
                            Advice advice = timeProfilerInterceptor;
                            Pointcut pointcut = new AnnotationMatchingPointcut(null, TimeProfiled.class);
                            this.advisor = new DefaultPointcutAdvisor(pointcut, advice);
                            }
                            }



                          3. Define your custom annotation to use where needed.



                            @Target(ElementType.METHOD)
                            @Retention(RetentionPolicy.RUNTIME)
                            public @interface TimeProfiled {

                            }



                          4. Tell Spring to initiate the wrapping mechanism at startup via the following annotation upon a Spring Configuration or a SpringBootApplication:



                            @ComponentScan(basePackageClasses = TimeProfiledAnnotationPostProcessor.class)
                            @EnableAspectJAutoProxy(proxyTargetClass = true)



                          You can change the pointcut so that it matches other methods with other criteria, there is an entire syntax to do that, a world in itself, this is just a small example...







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited 20 hours ago

























                          answered 20 hours ago









                          Evil Toad

                          1,2801022




                          1,2801022






























                               

                              draft saved


                              draft discarded



















































                               


                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53265930%2fwhere-to-write-common-code-in-spring-boot%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest




















































































                              Popular posts from this blog

                              Biblatex bibliography style without URLs when DOI exists (in Overleaf with Zotero bibliography)

                              ComboBox Display Member on multiple fields

                              Is it possible to collect Nectar points via Trainline?