Search code examples
springspring-mvcspring-bootspring-data-rest

How to use spring.data.rest.enable-enum-translation in Spring Data REST


I'm using Spring Boot 1.5.3, Spring Data REST, HATEOAS, Hibernate. In my model sometimes I'm using enum like:

    public enum Roles {
    ROLE_ADMIN, ROLE_USER, ROLE_MANAGER, ROLE_TECH
}

According to Spring Boot documentation, there is a property that seems useful:

# DATA REST (RepositoryRestProperties)
spring.data.rest.enable-enum-translation=true

I didn't find documentation about how to use that. I found old references where seems I should add something like:

roles.role_admin=Amministratore

in my messages.properties. That would be cool but it doesn't work and my REST reply contains enum value shown like in the class, without any translation. Could someone explain me the right way to use this function of Spring?


Solution

  • To use this feature you have to add a 'rest-messages' Resource Bundle to your project 'resources' folder. Then describe your enums in these files like this:

    com.example.myproject.myapp.Roles.ROLE_ADMIN=Amministratore
    com.example.myproject.myapp.Roles.ROLE_USER=Utente
    

    If you have a nested enums you have to join them and the parent class with '$' sign:

    com.example.myproject.myapp.User$Roles.ROLE_ADMIN=Amministratore
    com.example.myproject.myapp.User$Roles.ROLE_USER=Utente
    

    In the same manner you can describe your links:

    _links.user.title=Utente
    _links.users.title=Lista utenti
    

    Then you get something like this:

    "_links": {
        "user": {
            "href": "http://localhost:8080/api/users/1",
            "title": "Utente"
        }
    }
    
    "users": {
        "href": "http://localhost:8080/api/users{?page,size,sort}",
        "templated": true,
        "title": "Lista utenti"
    }
    

    There is also a little bit info in the SDR reference regarding to this issue.

    See Restbucks example.