如何使用Spring消息PropertyPlaceholderConfigurer传递参数?

时间:2018-03-09 09:10:05

标签: java spring spring-mvc properties-file

如果属性消息是硬编码的,则编写的代码工作正常。相反,我想将动态数据作为参数传递并获取消息。 我开发的代码是:

public class SpringPropertiesUtil extends PropertyPlaceholderConfigurer {

private static Map<String, String> propertiesMap;
// Default as in PropertyPlaceholderConfigurer
private int springSystemPropertiesMode = SYSTEM_PROPERTIES_MODE_FALLBACK; //Check system properties if not resolvable in the specified properties.

static final Logger logger = LogManager.getLogger(SpringPropertiesUtil.class);

@Override
public void setSystemPropertiesMode(int systemPropertiesMode) {
    super.setSystemPropertiesMode(systemPropertiesMode);
    springSystemPropertiesMode = systemPropertiesMode;
}

@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException {
    super.processProperties(beanFactory, props);

    propertiesMap = new HashMap<String, String>();
    for (Object key : props.keySet()) {
        String keyStr = key.toString();
        String valueStr = resolvePlaceholder(keyStr, props, springSystemPropertiesMode);
        propertiesMap.put(keyStr, valueStr);
    }
}

public static String getProperty(String name) {
    return propertiesMap.get(name).toString();
}

消息属性文件包括:

myProperty={0} how are you

现在,我希望在{0}的位置传递名称。但是我无法做到。如果要定义任何方法,请告诉我。

1 个答案:

答案 0 :(得分:3)

您可以自动装配消息源并使用 getMessage 方法,例如在控制器中:

...

@Autowired
private MessageSource messageSource;

...

final String[] params = new String[]{"Obama"};
final String msg = messageSource.getMessage("myProperty", params, LocaleContextHolder.getLocale());