Java中的@AllArgsConstructor注解(详解)

1. 基本知识

@AllArgsConstructor Lombok 提供的一个注解,用于自动生成一个包含所有参数的构造函数

简化构造函数的编写:通常情况下,Java 类中需要手动编写构造函数来初始化类的实例变量

使用 @AllArgsConstructor 注解可以自动生成一个包含所有实例变量的构造函数,减少编码量

使用方法

    • 引入依赖:在项目的依赖中加入 Lombok 库
    • 在类上添加注解:在需要使用该注解的类上添加 @AllArgsConstructor 注解

示例:

import lombok.AllArgsConstructor;

@AllArgsConstructor
public class MyClass {
    private String field1;
    private int field2;
    private double field3;
}

生成的构造函数如下:

public MyClass(String field1, int field2, double field3) {
    this.field1 = field1;
    this.field2 = field2;
    this.field3 = field3;
}

2. 实战

对于@Service注解中也可使用

@Service
@AllArgsConstructor
public class WireRopeReplaceOrderServiceImpl extends BaseServiceImpl<WireRopeReplaceOrderMapper, WireRopeReplaceOrder> implements IWireRopeReplaceOrderService {

	private IInfoService infoService;
	private IInfoRunningDataService iInfoRunningDataService;
	private IInfoWireropeDataService infoWireropeDataService;
	private IInfoRunningDataRopeService infoRunningDataRopeService;
	private RedisIdGeneratorService redisIdGeneratorService;

类似如下:

@Service
public class WireRopeReplaceOrderServiceImpl extends BaseServiceImpl<WireRopeReplaceOrderMapper, WireRopeReplaceOrder> implements IWireRopeReplaceOrderService {
	
	@Autowired
	private IInfoService infoService;
	@Autowired
	private IInfoRunningDataService iInfoRunningDataService;
	@Autowired
	private IInfoWireropeDataService infoWireropeDataService;
	@Autowired
	private IInfoRunningDataRopeService infoRunningDataRopeService;
	@Autowired
	private RedisIdGeneratorService redisIdGeneratorService;

猜你喜欢

转载自blog.csdn.net/2401_82767224/article/details/139987888