【问题标题】:Why message property return Null in Spring MVC为什么消息属性在 Spring MVC 中返回 Null
【发布时间】:2019-11-08 09:00:41
【问题描述】:

我正在做一个项目,我想将 消息外化。属性文件。这样运营团队就可以根据需求变化。

为此我写了一个这样的配置类

@Configuration
@ComponentScan(basePackages = {"lk.ideahub.symphony.modules", "lk.ideahub.symphony.product"})
@PropertySources(value = {@PropertySource(value = {"classpath:messages.properties"})})
public class MessageConfig {
    private static final Logger log = LoggerFactory.getLogger(MessageConfig.class);

    @Bean
    public MessageSource messageSource() {
        log.info("Message properties loading into the project");
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:messages");
        messageSource.setCacheSeconds(10);
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }
}

在消息属性中

axipay.failure.account.already.exist=Sorry, the biller account number is already added.

在我的课堂上

public Payee myPayees{

//Asking the property into a variable 
private static final String PAYEE_ACCOUNT_ALREADY_EXIST = "axipay.failure.account.already.exist";

@Autowired
Environment environment;

public void myMethod(){
 String message = getEnvironment().getProperty(PAYEE_ACCOUNT_ALREADY_EXIST);
}
}

【问题讨论】:

    标签: spring spring-mvc properties string-externalization


    【解决方案1】:

    可以使用spring提供的MessageSource Bean https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/MessageSource.html

    @Autowired
    private MessageSource messageSource;
    //use this method to get message
    public String getMessage(){        
    return messageSource.getMessage("axipay.failure.account.already.exist", null, new Locale("en"));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-30
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-12
      • 2016-11-14
      相关资源
      最近更新 更多