我们如何使用 lombok 为 2 个相同的对象创建相同的哈希码值?

问题描述 投票:0回答:1

我正在尝试单例设计模式。当我这样做时,service1和service2的hashcode值是相同的。但是我希望通过Lombok生成hashcode值。当我使用@EqualsAndHashCode注释时,service1和service2的hashcode值是输出不同。如何使用Lombok确保service1和service2的哈希值相同?我使用了@EqualsAndHashCode,但它没有达到我想要的效果。我也使用了@EqualsAndHashCode.Include,但它仍然不起作用。

@SpringBootApplication
@Slf4j
@RequiredArgsConstructor
public class DemoApplication implements CommandLineRunner {

    private final PaymentService service1;
    private final PaymentService service2;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void run(String... args) {
        log.info("service1 hashcode " + service1.hashCode());
        service1.setAmount(100L);
        service1.setPaymentStatus("success");
        log.info("service2 hashcode " + service2.hashCode());
        log.info("service2 amount " + service2.getAmount());
        log.info("service2 status " + service2.getPaymentStatus());
    }
}

@Getter
@Setter
public class PaymentService {
    private long amount;
    private String paymentStatus;
}

@Component
public class PaymentConfiguration {
    @Bean
    @Scope(value = "singleton")
    public PaymentService getPaymentService() {
        return new PaymentService();
    }
}
java singleton lombok
1个回答
0
投票

您可以使用

@EqualsAndHashCode
来注释您的课程:

@Getter
@Setter
@EqualsAndHashCode
public class PaymentService {
© www.soinside.com 2019 - 2024. All rights reserved.