Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to use Java Records with @Service / @RestController annotations

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();
    }
}
like image 964
Robert Vangor Avatar asked Sep 08 '25 02:09

Robert Vangor


1 Answers

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.

like image 162
Stanislav Bashkyrtsev Avatar answered Sep 10 '25 00:09

Stanislav Bashkyrtsev