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

坚强是说给别人听的谎言 提交于 2019-12-06 10:21:59

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/44800475/how-to-use-spring-data-rest-enable-enum-translation-in-spring-data-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!