简体   繁体   English

将配置数据传递给Java中DAO的具体实现

[英]Passing config data to concrete implementation of a DAO in Java

I am trying to implement a Data Access Object pattern with Abstract Factory to abstract out access to multiple data sources from the client code. 我正在尝试使用Abstract Factory实现数据访问对象模式,以从客户端代码中抽象出对多个数据源的访问。 I referred the below link. 我引用了以下链接。

http://www.oracle.com/technetwork/java/dataaccessobject-138824.html http://www.oracle.com/technetwork/java/dataaccessobject-138824.html

My question is:- How can I pass along configuration data (like path to a data file) from my client code into the concrete implementation of the DAO? 我的问题是:-如何将配置数据(例如数据文件的路径)从客户端代码传递到DAO的具体实现中?

In the link that I pasted above, under Example 9.2, there is an example of a concrete implementation where they are using hard-coded DBURL and DRIVER. 在上面粘贴的链接中,在示例9.2下,有一个具体实现的示例,其中,他们使用硬编码的DBURL和DRIVER。 What if these two needs to be passed along from the client code shown in Example 9.6? 如果需要从例9.6所示的客户端代码中传递这两个信息,该怎么办?

Add a plus parameter to DAOFactory.getDAOFactory function (for example a ConnectionParams object, where you store the connection url, user, etc.) and then pass that to your DAOFactory implementation's constructor. 将一个加参数添加到DAOFactory.getDAOFactory函数(例如,一个ConnectionParams对象,用于存储连接URL,用户等),然后将其传递给DAOFactory实现的构造函数。 After that your DAOFactory can use the ConnectionParams to create the connection. 之后,您的DAOFactory可以使用ConnectionParams创建连接。

The createConnection method mustn't be static in this case. 在这种情况下,createConnection方法不能为静态。

The ConnectionParams object can be like this: ` ConnectionParams对象可以像这样:

public class ConnectionParams {

    private String url;
    private String pass;
    private String file;

  /* getters and setters */
}

` `

If your DAOFactory implementation requires a file argument, it can use the file field. 如果您的DAOFactory实现需要一个file参数,则可以使用file字段。 The others can use the url, and the pass. 其他人可以使用url和密码。

The other solution is to get the required params from a common properties file, or from the System.properties. 另一种解决方案是从公用属性文件或System.properties中获取所需的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM