3

我和我的朋友正在创建一个程序并使用 SVN 共享代码。问题是我们在其中使用谷歌地图,所以我们需要我们所有人都有不同的 API 密钥。现在我们已经在应用程序中注释了我们的 API 密钥行,但是如果有人更改了该类并使用他的 API 提交,那就很烦人了。

有没有办法告诉不要将某些代码行提交给 SVN?

4

7 回答 7

5

从您的程序中删除硬编码,以便这些类是通用的(并且可以提交给 SVN)。

相反,将配置/API 密钥存储在外部配置文件或数据库中。增强代码以在应用程序启动时从您存储配置的任何位置加载配置。


更新:

这是一个用于创建和使用属性文件的非常简单的代码示例:http ://www.bartbusschots.ie/blog/?p=360

于 2011-12-14T11:43:35.290 回答
1

也许你可以使用一个文件 .properties,在那里你可以存储所有的 API 密钥,例如你可以调用一个属性 myAPIKey,其他的可以像 APIKey1、APIKey 2 这样调用。

如果这样做,您只需将要使用的属性的名称更改为 myAPIKey 并将其加载到您的 java 类中...

于 2011-12-14T11:45:01.370 回答
1

首先,配置不属于代码。编写一个 .properties 文件并将密钥和其余属性存储在那里。

之后,你应该

1)提交属性文件的副本(可能是properties_svn)

2)如果找不到后者,请让您的构建过程将 properties_svn 复制到 properties。

3) 享受

于 2011-12-14T11:46:06.103 回答
1

在 SVN 上存储密钥是不好的做法。这就像在那里存储您信用卡的密码一样。O 可能在信用卡本身上写密码。

这些密钥应该在您的私有环境中的 SVN 之外。如果您不想创建此类文件,请实现将键作为参数或系统属性传递的能力。

于 2011-12-14T11:46:34.820 回答
1

正如其他人已经说过的,正确的答案是“不要那样做”。

如果您必须确定最好将所有不同的键放在那里,然后在编译时(例如 C 预处理器)或运行时(例如基于hostname)选择正确的键。

于 2011-12-14T11:51:17.850 回答
1

您应该在代码外部保存这种类型的配置,通常在属性文件中,在运行时注入所需的值。

我通常使用一系列带有 Spring 的属性文件,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer每个都允许根据需要将属性值覆盖到特定用户,从而产生以下配置:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
  <property name="ignoreUnresolvablePlaceholders" value="true"/>
  <property name="ignoreResourceNotFound" value="true"/>
  <property name="order" value="1"/>
  <property name="locations">
    <list>
      <value>classpath:my-system.properties</value>
      <value>classpath:my-system-${HOST}.properties</value>
      <value>classpath:my-system-${USERNAME}.properties</value>
   </list>
  </property>
</bean>

如果您不使用 Spring,您可以在如下代码中实现相同的效果:

Properties properties = new Properties();

InputStream systemPropertiesStream = ClassLoader.getSystemResourceAsStream("my-system.properties");
if (systemPropertiesStream != null) 
{
  try
  {
    properties.load(systemPropertiesStream);
  }
  finally 
  {
    systemPropertiesStream.close();
  }  
}

InputStream hostPropertiesStream = ClassLoader.getSystemResourceAsStream("my-system" + InetAddress.getLocalHost().getHostName() + ".properties");
if (hostPropertiesStream != null) 
{
  try
  {
    properties.load(hostPropertiesStream);
  }
  finally 
  {
    hostPropertiesStream.close();
  }  
}

InputStream userPropertiesStream = ClassLoader.getSystemResourceAsStream("my-system" + System.getProperty("user.name") + ".properties");
if (userPropertiesStream != null) 
{
  try
  {
    properties.load(userPropertiesStream);
  }
  finally 
  {
    userPropertiesStream.close();
  }  
}    
于 2011-12-14T12:15:00.023 回答
0

通常这些东西不是源代码版本控制工具的一部分。大多数开发人员使用构建系统来解决这个或类似的问题。例如行家。

例如,使用 maven,有人会为具有不同 api 密钥或文件夹引用等的不同用户定义具有不同属性文件的不同配置文件。

于 2011-12-14T11:43:55.927 回答