详细分析Java中的@AllArgsConstructor注解

发布于:2024-06-11 ⋅ 阅读:(14) ⋅ 点赞:(0)

前言

事情起因是Spring的循环依赖

详情可见:出现The dependencies of some of the beans in the application context form a cycle 解决方法(全)

1. 基本知识

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

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

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

使用方法

  1. 引入依赖:在项目的依赖中加入 Lombok 库
  2. 在类上添加注解:在需要使用该注解的类上添加 @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;