@Nullable 注解的详细用法

背景

最近发现之前写的代码生成器(entity、dao、service、controller、vue) 有点bug,在Service层判断空的时候,少了一部分条件。所以补充上了,随后又同事问我在代码中发下了@Nullable注解不知道怎么用?脑子是个好东西,可以审核没带啊!哪有广告?

起初,以为这么简单的一个常用注解还不了解吗?

用法

@Nullable可以用在方法、属性、参数上。对应的意思分别如下:

方法:表示返回值可以是空

属性:表示属性值可以是空

参数:表示参数值可以是空

用在方法上

方法的返回值可以是为空,具体的用法如下方代码所示:

@Nullable
public ApiResult upload(@NotNull(message = "上传参数不能为空") @RequestParam("file") MultipartFile[] file) throws BaseException {
    ApiResult apiResult = new ApiResult();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
    String format = simpleDateFormat.format(new Date());
    String realPath = filePath + File.separator + format;
    String returnPath = format;
    File targetFile = new File(realPath);
    if (!targetFile.exists()){
        targetFile.mkdirs();
    }
}

将注解用在方法商法,就可以表示这个方法的返回值可以是空。就是这么简单。

用在参数上

参数可以是为空,具体的用法如下方代码所示:

private void checkUser(String fansid, String openid, @Nullable String op) throws BaseException{
    Consumer consumer = consumerService.selectByPrimaryKey(fansid);
    if (consumer == null) {
        throw new ParamException("用户不存在");
    }
    Consumer consumer1 = consumerService.selectByPrimaryKey(openid);
    if(consumer1 == null){
        throw new ParamException("被关注者信息异常");
    }
}

用在参数上的方法也很简单,就是在参数前方加一个@Nullable注解,这样标识为这个参数可以为空。

用在属性上

属性可以为空,具体参考代码如下:

@Validated
@RestController
@RequestMapping("miniapi/follow")
public class FollowController extends BaseController {
    @Nullable
    private String isTime;
    
    @Autowired
    private FollowService followService;
    @Autowired
    private ConsumerService consumerService;
    private Logger logger = LoggerFactory.getLogger(this.getClass());
  }  

从上方我们解决的部分代码可以看出,这部分代码中在属性isTime上方标记了@Nullable注解,标识这个isTime属性可以为空。

以上,就是我们自己在使用的中的真实案例,那在我们平常引用第三方包结构中有没有引用案例呢?

Spring工具包源码中的使用案例

org.springframework.util.StringUtils中的判断空方法中用到了此方法。

就是我们所属的用在参数上面的示例:

public static boolean isEmpty(@Nullable Object str) {
   return (str == null || "".equals(str));
}

好了,今天关于@Nullable的使用情况闲聊到这,欢迎朋友们留言交流。

也希望大家关注我的《coder练习生》

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ybb_ymm

你的鼓励会是对我最大的支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值