I'd prefer it as a record as there is less boilerplate, but would there be issues?
IntelliJ is suggesting that I turn a basic Java class @Service like this:
@Service
public class LocationService {
private final PlaceRepository placeRepository;
@Autowired
public LocationService(PlaceRepository placeRepository) {
this.placeRepository = placeRepository;
}
public List<PlaceDto> findPlacesByRegionId(Long regionId){
return placeRepository.findByRegionId(regionId).stream().map(place -> new PlaceDto(place.getId(), place.getName())).toList();
}
}
into a Java record @Service like this:
@Service
public record LocationService(PlaceRepository placeRepository) {
public List<PlaceDto> findPlacesByRegionId(Long regionId) {
return placeRepository.findByRegionId(regionId).stream().map(place -> new PlaceDto(place.getId(), place.getName())).toList();
}
}
You could do that, but records have getters (without the get
prefix though), which Service Layer shouldn't have.
In addition, your Service Facade exposes public methods which are usually @Transactional
. You don't want to mix them with methods that no one is going to use.
Also, records define equals()
& hashCode()
, which aren't needed for Service classes either.
In the end, the only common theme between Records and Services is that all fields are usually final
and all of them are usually passed via constructor. This isn't much of commonality. So it sounds like a bad idea to use records for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With