Where to write Common code in spring boot












0














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



























    0














    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

























      0












      0








      0


      0





      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 Nov 12 '18 at 16:06









      Shiva

      198




      198
























          2 Answers
          2






          active

          oldest

          votes


















          0














          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































            0














            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





















              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%2f53265930%2fwhere-to-write-common-code-in-spring-boot%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









              0














              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




























                0














                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


























                  0












                  0








                  0






                  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 Nov 12 '18 at 17:02

























                  answered Nov 12 '18 at 16:55









                  Evil Toad

                  1,3451022




                  1,3451022

























                      0














                      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


























                        0














                        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
























                          0












                          0








                          0






                          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 Nov 12 '18 at 16:50









                          rieckpil

                          1,1811617




                          1,1811617






























                              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.





                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                              Please pay close attention to the following guidance:


                              • 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%2f53265930%2fwhere-to-write-common-code-in-spring-boot%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







                              這個網誌中的熱門文章

                              Hercules Kyvelos

                              Tangent Lines Diagram Along Smooth Curve

                              Yusuf al-Mu'taman ibn Hud