Lombok @RequiredArgsConstructor 注解

大家平时使用spring依赖注入,都是怎么写的?

@RestController
@RequestMapping("alarm/configs")
public class AlarmConfigController {
    @Autowired
    private AlarmConfigService alarmConfigService;
...
}

是不是很熟悉的感觉?但是呢 如果你用IDEA的话呢,它会提示你

大概就是spring 不推荐建使用这个方式。原因网上很多啦:https://blog.csdn.net/github_38222176/article/details/79506392

下面就是spring推荐的写法:

@RestController
@RequestMapping("alarm/configs")
public class AlarmConfigController {
    private final AlarmConfigService alarmConfigService;

    @Autowired
    public AlarmConfigController(AlarmConfigService alarmConfigService) {
        this.alarmConfigService = alarmConfigService;
    }
...
}

若是注入的类太多的话呢,看起来挺繁琐的。最近偶然在网上发现使用Lombok可以写出简洁的代码:

后发现该方法有几率导致Spring循环引用问题,所以还是不推荐使用

@RestController
@RequestMapping("alarm/configs")
@RequiredArgsConstructor
public class AlarmConfigController {
    //这里必须是final,若不使用final,用@NotNull注解也是可以的
    private final AlarmConfigService alarmConfigService;
...
}

 这样写实际上编译后和spring推荐的写法是一样的哦,是不是很简洁

参考https://my.oschina.net/yejunxi/blog/2209101

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值