我正在尝试单例设计模式。当我这样做时,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();
}
}