dangsn
2024-06-06 33321f5486fd586fda6fd3f46b7e71754fede28b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.vci.starter.web.util;
 
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
 
/**
 * 国际化工具
 * @author weidy
 * @date 2019/11/7 2:41 PM
 */
@Component
public class MessageUtils {
 
    /**
     * 注入国际化资源镜像
     */
    private static MessageSource messageSource;
 
    /**
     * 构造函数
     * @param messageSource 国际化资源
     */
    public MessageUtils(MessageSource messageSource) {
        MessageUtils.messageSource = messageSource;
    }
 
    /**
     * 获取单个国际化翻译值
     * @param msgKey 资源代号
     * @return 翻译后的值
     */
    public static String get(String msgKey) {
        try {
            return messageSource.getMessage(msgKey, null, LocaleContextHolder.getLocale());
        } catch (Throwable e) {
            return msgKey;
        }
    }
 
    /**
     * 获取单个国际化翻译值
     * @param msgKey 资源代号
     * @param objects 翻译时使用的对象
     * @return 翻译后的值
     */
    public static String get(String msgKey,Object[] objects){
        try {
            return messageSource.getMessage(msgKey, objects, LocaleContextHolder.getLocale());
        } catch (Throwable e) {
            return msgKey;
        }
    }
}