减少代码臃肿,不用重复使用autowired

当使用@autowired注入的时候,有时候会发生警告(我之前的采取方法无非就是替换成resource注解)或者采用构造器的方法进行注入但是今天了解到了@RequiredArgsConstructor

 @RequiredArgsConstructor注解

  • 该注解作用于类上
  • 标记为final的对象,会自动进行注入
  • 使用lombok的 @NonNull 注解标记的对象,会自动进行注入
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class ZTestController implements CommandLineRunner {
	
	// 支付宝支付
    private AliaPay aliaPay;
	
	// 京东支付
    private JingDongPay jingDongPay;
	
	// 使用构造方法进行注入(😵如果要注入多个对象会让构造器变得臃肿)
    @Autowired
    public ZTestController(AliaPay aliaPay, JingDongPay jingDongPay) {
        this.aliaPay = aliaPay;
        this.jingDongPay = jingDongPay;
    }

    @Override
    public void run(String... args) throws Exception {
		
		// 调用完成支付
        aliaPay.pay();
        jingDongPay.pay();
    }
}

使用后

import lombok.NonNull;
import lombok.RequiredArgsConstructor;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
// 使用lombok的@RequiredArgsConstructor注解进行注入
@RequiredArgsConstructor
public class ZTestController implements CommandLineRunner {
	
	// 标记为final的,会自动进行注入
    private final AliaPay aliaPay;
	
	// 使用lombok的@NonNull注解标记的,会自动进行注入
    @NonNull
    private JingDongPay jingDongPay;
	
	// 未标记final或@NonNull,不会进行注入
    private WeixinPay weixinPay;

    @Override
    public void run(String... args) throws Exception {

        aliaPay.pay();

        jingDongPay.pay();

        if (weixinPay == null) {
            System.out.println("WeixinPay注入失败");
        }
    }
}

代码取自@SpringBoot 使用lombok的@RequiredArgsConstructor注解进行Bean注入_@interface lombok.requiredargsconstructor_fengyehongWorld的博客-CSDN博客

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐