如果给定条件为假,如何编写注释/方面不输入方法但返回 null? [英] How to write an annotation/aspect to not enter a method but return null if a given condition is false?
问题描述
我目前有一个要求,如果给定条件为假,我需要从 100 个方法中返回 null.我正在考虑为此使用 Java Annotations 或 Spring Aspects,这样我就不必到处编写 if-else 代码块.关于我们如何使用 Java Annotations 或 Spring Aspects 做到这一点的任何想法?
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 this so that I don't have to write that if-else block of code everywhere. Any idea as to how we can do this using Java Annotations or Spring Aspects?
任何提示都可能有帮助.
Any pointers might be helpful.
推荐答案
如果我理解正确,Spring @Conditional
注释就是你想要的.您创建了一些实现 Spring 的 Condition
接口的公共类:
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!
这篇关于如果给定条件为假,如何编写注释/方面不输入方法但返回 null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!