How to write an annotation/aspect to not enter a method but return null if a given condition is false?

前端 未结 2 1175
长发绾君心
长发绾君心 2021-01-26 20:20

I currently have a requirement where I need to return null from 100s of methods if a given condition is false. I was thinking of using Java Annotations or Spring Aspects for thi

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-26 20:37

    If I get you correctly, Spring @Conditional annotation is what you want. You create some public class that implements Spring's Condition interface:

    public class Test implements Condition {
    ...
    }
    

    Then you use the forementioned annotation with the parameter which takes as an argument that public class.

    @Conditional(Test.class)
    public Object someMethod(boolean context){
    /*and so do some logics; if the value of 'context' variable is false, you can return 
    null; otherwise, just return like this*/
    return new someMethodImpl1();
    }
    

    Hope I helped. And I'm glad of any kind of corrections. Cheers!

提交回复
热议问题