How validate method parameters are NotNull by default in spring method validation?












2















Here is example about method validation. So check method paramerter as not null I have to write the follolwing:



import org.springframework.validation.annotation.Validated

@Validated
public class SomeClass {
public void myMethod(@NotNull Object p1, @Nullable Object p2) {}
}


Is there a way to setup spring bean validation to make all parameters validated as @NotNull by default? E.g. the following will fail when p1 is null:



import org.springframework.validation.annotation.Validated

@Validated
public class SomeClass {
public void myMethod(Object p1, @Nullable Object p2) {}
}


Any ideas?










share|improve this question























  • what exactly do you want to achieve?

    – stacker
    Nov 20 '18 at 14:22











  • Reduce annotations on method parameters.

    – Cherry
    Nov 27 '18 at 12:49
















2















Here is example about method validation. So check method paramerter as not null I have to write the follolwing:



import org.springframework.validation.annotation.Validated

@Validated
public class SomeClass {
public void myMethod(@NotNull Object p1, @Nullable Object p2) {}
}


Is there a way to setup spring bean validation to make all parameters validated as @NotNull by default? E.g. the following will fail when p1 is null:



import org.springframework.validation.annotation.Validated

@Validated
public class SomeClass {
public void myMethod(Object p1, @Nullable Object p2) {}
}


Any ideas?










share|improve this question























  • what exactly do you want to achieve?

    – stacker
    Nov 20 '18 at 14:22











  • Reduce annotations on method parameters.

    – Cherry
    Nov 27 '18 at 12:49














2












2








2








Here is example about method validation. So check method paramerter as not null I have to write the follolwing:



import org.springframework.validation.annotation.Validated

@Validated
public class SomeClass {
public void myMethod(@NotNull Object p1, @Nullable Object p2) {}
}


Is there a way to setup spring bean validation to make all parameters validated as @NotNull by default? E.g. the following will fail when p1 is null:



import org.springframework.validation.annotation.Validated

@Validated
public class SomeClass {
public void myMethod(Object p1, @Nullable Object p2) {}
}


Any ideas?










share|improve this question














Here is example about method validation. So check method paramerter as not null I have to write the follolwing:



import org.springframework.validation.annotation.Validated

@Validated
public class SomeClass {
public void myMethod(@NotNull Object p1, @Nullable Object p2) {}
}


Is there a way to setup spring bean validation to make all parameters validated as @NotNull by default? E.g. the following will fail when p1 is null:



import org.springframework.validation.annotation.Validated

@Validated
public class SomeClass {
public void myMethod(Object p1, @Nullable Object p2) {}
}


Any ideas?







java spring jsr380






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 '18 at 13:34









CherryCherry

9,0902392168




9,0902392168













  • what exactly do you want to achieve?

    – stacker
    Nov 20 '18 at 14:22











  • Reduce annotations on method parameters.

    – Cherry
    Nov 27 '18 at 12:49



















  • what exactly do you want to achieve?

    – stacker
    Nov 20 '18 at 14:22











  • Reduce annotations on method parameters.

    – Cherry
    Nov 27 '18 at 12:49

















what exactly do you want to achieve?

– stacker
Nov 20 '18 at 14:22





what exactly do you want to achieve?

– stacker
Nov 20 '18 at 14:22













Reduce annotations on method parameters.

– Cherry
Nov 27 '18 at 12:49





Reduce annotations on method parameters.

– Cherry
Nov 27 '18 at 12:49












2 Answers
2






active

oldest

votes


















0














You can write your own @NotNullArgs annotation as an option



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


And aspect:



@Aspect
@Component
public class ArgumentMatcher {

@Around(value = "@annotation(NotNullArgs)")
public Object verifyAuthorities(ProceedingJoinPoint joinPoint) throws Throwable {
final Optional<Object> nullArg = Arrays.stream(joinPoint.getArgs())
.filter(Objects::isNull)
.findFirst();

if (nullArg.isPresent() && joinPoint.getArgs().length > 0) {
throw new IllegalArgumentException(); // or NPE
} else {
return joinPoint.proceed();
}
}
}


Then you can use it like this:



@NotNullArgs
void methodToCall(Obj arg1, Obj arg2) { .... }


It's just a draft, but you can use this code as a point to start






share|improve this answer

































    0














    If you would like Spring to automatically validate method arguments do this:




    1. add org.hibernate.validator:hibernate-validator to your dependencies

    2. mark the required method arguments with @javax.validation.constraints.NotNull


    then when you call such method and do not provide the required argument you will get a javax.validation.ConstraintViolationException exception.



    another approach, a lot easier, is to use Lombok's: just mark the method argument with @lombok.NonNull and Lombok will do the rest.






    share|improve this answer


























    • mark the required methods with this what I want to skip regardless of spring or hgibernate validation.

      – Cherry
      Nov 20 '18 at 18:13











    • @Cherry you want all the method arguments to be by default required?

      – Adam Siemion
      Nov 20 '18 at 23:03











    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%2f53394216%2fhow-validate-method-parameters-are-notnull-by-default-in-spring-method-validatio%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














    You can write your own @NotNullArgs annotation as an option



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


    And aspect:



    @Aspect
    @Component
    public class ArgumentMatcher {

    @Around(value = "@annotation(NotNullArgs)")
    public Object verifyAuthorities(ProceedingJoinPoint joinPoint) throws Throwable {
    final Optional<Object> nullArg = Arrays.stream(joinPoint.getArgs())
    .filter(Objects::isNull)
    .findFirst();

    if (nullArg.isPresent() && joinPoint.getArgs().length > 0) {
    throw new IllegalArgumentException(); // or NPE
    } else {
    return joinPoint.proceed();
    }
    }
    }


    Then you can use it like this:



    @NotNullArgs
    void methodToCall(Obj arg1, Obj arg2) { .... }


    It's just a draft, but you can use this code as a point to start






    share|improve this answer






























      0














      You can write your own @NotNullArgs annotation as an option



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


      And aspect:



      @Aspect
      @Component
      public class ArgumentMatcher {

      @Around(value = "@annotation(NotNullArgs)")
      public Object verifyAuthorities(ProceedingJoinPoint joinPoint) throws Throwable {
      final Optional<Object> nullArg = Arrays.stream(joinPoint.getArgs())
      .filter(Objects::isNull)
      .findFirst();

      if (nullArg.isPresent() && joinPoint.getArgs().length > 0) {
      throw new IllegalArgumentException(); // or NPE
      } else {
      return joinPoint.proceed();
      }
      }
      }


      Then you can use it like this:



      @NotNullArgs
      void methodToCall(Obj arg1, Obj arg2) { .... }


      It's just a draft, but you can use this code as a point to start






      share|improve this answer




























        0












        0








        0







        You can write your own @NotNullArgs annotation as an option



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


        And aspect:



        @Aspect
        @Component
        public class ArgumentMatcher {

        @Around(value = "@annotation(NotNullArgs)")
        public Object verifyAuthorities(ProceedingJoinPoint joinPoint) throws Throwable {
        final Optional<Object> nullArg = Arrays.stream(joinPoint.getArgs())
        .filter(Objects::isNull)
        .findFirst();

        if (nullArg.isPresent() && joinPoint.getArgs().length > 0) {
        throw new IllegalArgumentException(); // or NPE
        } else {
        return joinPoint.proceed();
        }
        }
        }


        Then you can use it like this:



        @NotNullArgs
        void methodToCall(Obj arg1, Obj arg2) { .... }


        It's just a draft, but you can use this code as a point to start






        share|improve this answer















        You can write your own @NotNullArgs annotation as an option



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


        And aspect:



        @Aspect
        @Component
        public class ArgumentMatcher {

        @Around(value = "@annotation(NotNullArgs)")
        public Object verifyAuthorities(ProceedingJoinPoint joinPoint) throws Throwable {
        final Optional<Object> nullArg = Arrays.stream(joinPoint.getArgs())
        .filter(Objects::isNull)
        .findFirst();

        if (nullArg.isPresent() && joinPoint.getArgs().length > 0) {
        throw new IllegalArgumentException(); // or NPE
        } else {
        return joinPoint.proceed();
        }
        }
        }


        Then you can use it like this:



        @NotNullArgs
        void methodToCall(Obj arg1, Obj arg2) { .... }


        It's just a draft, but you can use this code as a point to start







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 20 '18 at 14:34

























        answered Nov 20 '18 at 14:16









        Rostyslav BarmakovRostyslav Barmakov

        1193




        1193

























            0














            If you would like Spring to automatically validate method arguments do this:




            1. add org.hibernate.validator:hibernate-validator to your dependencies

            2. mark the required method arguments with @javax.validation.constraints.NotNull


            then when you call such method and do not provide the required argument you will get a javax.validation.ConstraintViolationException exception.



            another approach, a lot easier, is to use Lombok's: just mark the method argument with @lombok.NonNull and Lombok will do the rest.






            share|improve this answer


























            • mark the required methods with this what I want to skip regardless of spring or hgibernate validation.

              – Cherry
              Nov 20 '18 at 18:13











            • @Cherry you want all the method arguments to be by default required?

              – Adam Siemion
              Nov 20 '18 at 23:03
















            0














            If you would like Spring to automatically validate method arguments do this:




            1. add org.hibernate.validator:hibernate-validator to your dependencies

            2. mark the required method arguments with @javax.validation.constraints.NotNull


            then when you call such method and do not provide the required argument you will get a javax.validation.ConstraintViolationException exception.



            another approach, a lot easier, is to use Lombok's: just mark the method argument with @lombok.NonNull and Lombok will do the rest.






            share|improve this answer


























            • mark the required methods with this what I want to skip regardless of spring or hgibernate validation.

              – Cherry
              Nov 20 '18 at 18:13











            • @Cherry you want all the method arguments to be by default required?

              – Adam Siemion
              Nov 20 '18 at 23:03














            0












            0








            0







            If you would like Spring to automatically validate method arguments do this:




            1. add org.hibernate.validator:hibernate-validator to your dependencies

            2. mark the required method arguments with @javax.validation.constraints.NotNull


            then when you call such method and do not provide the required argument you will get a javax.validation.ConstraintViolationException exception.



            another approach, a lot easier, is to use Lombok's: just mark the method argument with @lombok.NonNull and Lombok will do the rest.






            share|improve this answer















            If you would like Spring to automatically validate method arguments do this:




            1. add org.hibernate.validator:hibernate-validator to your dependencies

            2. mark the required method arguments with @javax.validation.constraints.NotNull


            then when you call such method and do not provide the required argument you will get a javax.validation.ConstraintViolationException exception.



            another approach, a lot easier, is to use Lombok's: just mark the method argument with @lombok.NonNull and Lombok will do the rest.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 21 '18 at 15:02

























            answered Nov 20 '18 at 15:13









            Adam SiemionAdam Siemion

            11.8k13368




            11.8k13368













            • mark the required methods with this what I want to skip regardless of spring or hgibernate validation.

              – Cherry
              Nov 20 '18 at 18:13











            • @Cherry you want all the method arguments to be by default required?

              – Adam Siemion
              Nov 20 '18 at 23:03



















            • mark the required methods with this what I want to skip regardless of spring or hgibernate validation.

              – Cherry
              Nov 20 '18 at 18:13











            • @Cherry you want all the method arguments to be by default required?

              – Adam Siemion
              Nov 20 '18 at 23:03

















            mark the required methods with this what I want to skip regardless of spring or hgibernate validation.

            – Cherry
            Nov 20 '18 at 18:13





            mark the required methods with this what I want to skip regardless of spring or hgibernate validation.

            – Cherry
            Nov 20 '18 at 18:13













            @Cherry you want all the method arguments to be by default required?

            – Adam Siemion
            Nov 20 '18 at 23:03





            @Cherry you want all the method arguments to be by default required?

            – Adam Siemion
            Nov 20 '18 at 23:03


















            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%2f53394216%2fhow-validate-method-parameters-are-notnull-by-default-in-spring-method-validatio%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

            'app-layout' is not a known element: how to share Component with different Modules

            android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

            WPF add header to Image with URL pettitions [duplicate]