java - 在 Spring 中使用属性文件

标签 java spring

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

Transaction Name     Transaction Id
TXT_CCO              = 70001
TXT_CCI              = 70002
TXT_SSM              = 20005

在我的 Controller 中,有一个操作如下。

@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。例如,如果提供商是 TXT_CCO,交易类型 ID 应为 70001

有人可以帮我实现这个目标吗

最佳答案

我想说你有两个选择

  1. 使用 <util:properties /> 加载属性
  2. 使用@PropertySourceEnvironment抽象。

使用 <util:properties />

要简单地加载属性文件,您可以使用 PropertiesFactoryBean或者更容易 <util:properties />标签(它使用下面的PropertiesFactoryBean,但更容易配置)。请参阅here了解更多信息。

只需将以下内容添加到您的 xml 配置

<util:properties id="transactions" location="classpath:transaction.properties" />

现在你有一个Properties名为 transactions 的 bean您可以将其注入(inject)到您的 Controller 中,然后您可以使用它来获取您需要的属性。

@Autowired
private Properties transactions;

使用 @PropertySourceEnvironment抽象

另一个解决方案是添加 @Configuration@PropertySource加载属性。之后您可以使用Environment来获得属性。请参阅 Environment 引用指南中的部分了解更多信息。

@Configuration
@PropertySource("classpath:transaction.properties")
public class MyConfiguration {}

在您的 Controller 中,您可以使用 Environment获取属性。

@Autowired
private Environment env;

资源支持

当然,Spring 属性支持可与 Resource loading 一起使用。 Spring 临近。所以file:http:前缀以及适用于使用的 ApplicationContext 的默认加载规则也有效。 .

关于java - 在 Spring 中使用属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32195550/

相关文章:

java - 确认传递到 Spring Rest Endpoint 的 RequestBody 的无效输入的方法

集群中的 spring 集成 + cron + quartz ?

spring - 使用 Spring Boot 进行内存身份验证

java - Spring Boot带附件的邮件发送

java - 如何防止在模板中使用环境变量?

java - AppEngine 数据存储区 Java 中的嵌入式实体列表

java - 安卓 : Problems with accents and ñ

java - 大型项目的 Eclipse Content Assist Slowness

java - 是 equals() 和 toHashCode 影响 vector add() remove() 方法的行为

java - 使用 System.out.format 和 System.out.println 进行多线程