O
O
Orkhan Hasanli2019-10-14 01:34:44
Java
Orkhan Hasanli, 2019-10-14 01:34:44

How to get translation dynamically from properties for Enum and insert into the right document?

Hello!
I am writing a small web application. It is necessary to add data from DTO to docx using docx-stamper (docx4j).
For enum in messages.properties I store translations. If you directly insert values ​​from DTO, then enum is added. not his translation. Hence the question - How to dynamically get the translation from properties for Enum and insert it into the right document?

// Сформировать docx из DTO
    public void createDocXFromDTO(DischargeDTO dischargeDTO) throws Exception {
        InputStream template = new FileInputStream("discharge.docx");
        OutputStream out = new FileOutputStream("newDischarge.docx");
        DocxStamper stamper = new DocxStamperConfiguration()
                .build();
        stamper.stamp(template, dischargeDTO, out);
        out.close();
}

The DTO itself, which contains the Enum
@Setter  @Getter
public class DischargeDTO {
    private Long dischargeId;
    private LocalDate dob;
    private Sex sex;
}

Well, the contents of messages.properties, where translations of enum values ​​are stored
# Enum Sex
info.test.models.enums.Sex.MAN = мужчина
info.test.models.enums.Sex.WOMAN = женщина

I need to insert their translations (Man, Woman) instead of the enum values ​​themselves (MAN, WOMAN).
I understand that in DTO I need to form it ... but here's how ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2019-10-18
@azerphoenix

Found the solution on github.
I provide the source code below:

@Component
public class Messages {

    @Autowired
    private MessageSource messageSource;

    private MessageSourceAccessor accessor;

    @PostConstruct
    private void init() {
        accessor = new MessageSourceAccessor(messageSource, LocaleContextHolder.getLocale());
    }
    public String get(String code) {
        return accessor.getMessage(code);
    }
}

When needed, just use
@Autowired
private Messages messages;

(it's better to use a constructor, of course)
Well,
messages.get("info.md7.urodocs.models.enums.Sex.MAN")

There were reasons why I didn't use @Valueor @ConfigurationPropertiesin this case.
Well, accordingly, the contents of messages.properties
info.test.models.enums.Sex.MAN = мужчина
info.test.models.enums.Sex.WOMAN = женщина

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question