Java 在Spring中使用属性文件

Java 在Spring中使用属性文件,java,spring,Java,Spring,我是Spring框架的新手。在我的Spring应用程序中,有一些细节如下,这些细节需要在属性文件中维护 Transaction Name Transaction Id TXT_CCO = 70001 TXT_CCI = 70002 TXT_SSM = 20005 在我的控制器中,有一个操作如下 @RequestMapping(value = {"/ValidateWalletAmount**"}, metho

我是Spring框架的新手。在我的Spring应用程序中,有一些细节如下,这些细节需要在属性文件中维护

Transaction Name     Transaction Id
TXT_CCO              = 70001
TXT_CCI              = 70002
TXT_SSM              = 20005
在我的控制器中,有一个操作如下

@RequestMapping(value = {"/ValidateWalletAmount**"}, method = RequestMethod.GET)
public @ResponseBody String validateWalletAmount(@RequestParam("mobile") String mobile,
                                           @RequestParam("pin") String merchant_pin,
                                           @RequestParam("provider") String provider,
                                           @RequestParam("currency_type") String currency_type,
                                           @RequestParam("amount") String amount) {
    //TO DO - Get txnTypeId by provider

    return "02 | 1000.00 | 0.00";
}
根据请求参数provider我需要获取相关的交易类型id。例如,如果provider是TXT\u CCO交易类型id应该是70001


有人能帮我实现这一点吗?

假设您的属性文件名为“messages.properties”,在这种情况下,您的applicationContext.xml文件中需要类似于以下内容的内容

<bean id="messageSource"
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basenames" value="classpath:messages" />
    <property name="defaultEncoding" value="UTF-8" />
</bean>
要比较交易类型id,您可以使用如下代码:

   if(provider.trim().equals("TXT_CCO")){
        String transactionTypeId=messageSource.getMessage("TXT_CCO", null, Locale.ENGLISH).trim();
    }

我想你有两个选择

  • 使用
  • 使用
    @PropertySource
    环境
    抽象
  • 使用
    要简单地加载属性文件,您可以使用
    PropertiesFactoryBean
    或更简单的
    标记(下面使用
    PropertiesFactoryBean
    ,但更容易配置)。有关更多信息,请参阅

    @Configuration
    @PropertySource("classpath:transaction.properties")
    public class MyConfiguration {}
    
    只需将以下内容添加到xml配置中

    <util:properties id="transactions" location="classpath:transaction.properties" />
    
    使用
    @PropertySource
    环境
    抽象 另一个解决方案是添加一个带有
    @PropertySource
    @Configuration
    类来加载属性。之后,您可以使用
    环境
    获取属性。有关更多信息,请参阅参考指南中的部分

    @Configuration
    @PropertySource("classpath:transaction.properties")
    public class MyConfiguration {}
    
    在控制器中,您可以使用
    环境
    获取属性

    @Autowired
    private Environment env;
    
    资源支持


    当然,Spring属性支持在Spring方法中是可用的。因此
    file:
    http:
    前缀也可以工作,以及应用于所用
    ApplicationContext的默认加载规则

    您尝试了什么?你面临什么问题?因为这太过分了broad@Ann基本上,您需要将属性文件值作为映射对象注入控制器类中。您还可以看看这个答案:对于消息解析和I18N支持来说,这不是正确的方法。要简单地加载属性文件,请使用
    ,并简单地将生成的
    属性
    对象插入控制器中。
    @Autowired
    private Environment env;