2013-02-02 95 views

回答

2

如果你打算亲自去做,我建议你创建一个配置类,它通过构造函数接受文件,并将属性值读入成员变量。然后每个需要配置的类都通过它的构造函数接受一个Configuration类。但是,几乎没有人这样做,而是使用像Spring这样的框架,它为您处理属性注入。

在春天,它会是这个样子:

<!-- application context xml file --> 
<context:property-placeholder location="file:///some/path/to/file" /> 
在Java类中

然后:

public class SomeClass { 
    @Value("${some.property}") 
    private String someProp; 

    @Value("${some.other.prop}") 
    private Integer someOtherProp; 

    // ... 
} 

启动应用程序时性能得到注入类。

0

我的建议是有一个Util类加载属性文件并从该Util获取值到所需的类。

注意:我不认为你有任何加载属性文件的问题。

0

我建议你创建一个不可变的类,它接受文件作为构造函数参数并设置所有的实例变量。我会称之为PropertyConfiguration。然后,因为课程是不可改变的,所以您不必担心将其传递给每个人。你甚至可以拥有一个拥有它的课程。

例如,下面的代码会让你有一个很好的设置,以便在项目范围内有几件事情可用。我只是要确保共享的任何东西都是不可变的,以确保线程安全。

public class ClientUtils { 

    private static ClientContext _clientContext = null; 

    public static void setClientContext(ClientContext cc) { 
     _clientContext = cc; 
    } 

    public static ClientContext getContext() { 
     return _clientContext; 
    } 
} 

public class ClientContext { 

    private final Configuration _configuration; 

    public ClientContext(Configuration config){ 
     _configuration = config; 
    } 

    public Configuration getClientContext() { 
     return _configuration; 
    } 

} 
0

如果你的程序中包含它不必是编译的一部分,可以从部署到部署的变化数据,你必须把它加到属性文件:(比如像数据库连接字符串,电子邮件地址)。

为了防止您需要此操作,我添加了访问属性文件的代码。 删除文件build目录。

Properties properties = new Properties();  
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("credentials.properties"));