I have been experimenting with spring-data-rest (SDR) and am really impressed with how quickly I can build a rest api. My application is based around the following repository which gives me GET /attachements and POST /attachements
package com.deepskyblue.attachment.repository; import java.util.List; import org.springframework.data.repository.Repository; import com.deepskyblue.attachment.domain.Attachment; public interface AttachmentRepository extends Repository<Attachment, Long> { List<Attachment> findAll(); Attachment save(Attachment attachment); }
One thing I am confused about though is how I add custom business logic. SDR seems great if I just want a rest API to my data, however a traditional Spring application would normally have a service tier where I can have business logic. Is there a way of adding this business logic with SDR?
There are many possibilities.
Validators (http://docs.spring.io/spring-data/rest/docs/current/reference/html/#validation) for validating received objects.
Event Handlers http://docs.spring.io/spring-data/rest/docs/current/reference/html/#events) that will be called when validation was okay.
Custom Controllers (http://docs.spring.io/spring-data/rest/docs/current/reference/html/#customizing-sdr.overriding-sdr-response-handlers) when you manually want to handle the request.
I ended up creating a custom Aspect that's around repository method. Something like this (groovy):
@Aspect @Component @Slf4j class AccountServiceAspect { @Around("execution(* com.test.accounts.account.repository.AccountRepository.save*(..))") Object saveAccount(ProceedingJoinPoint jp) throws Throwable { log.info("in aspect!") Object[] args = jp.getArgs() if (args.length <= 0 || !(args[0] instanceof Account)) return jp.proceed() Account account = args[0] as Account account.active = true jp.proceed(account) } }
Not ideal but you can modify model before saving it without writing spring data rest controllers from scratch.
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