jax-rs rest服务调用属性文件

jax-rs rest service calling properties files

上下文

我按照这个 SO answer 创建并加载了一个属性文件。

我的后端代码分为 4 个项目(服务、业务、DAO、模型)

服务

@Path("/users")
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<User> getUsers() {
    return UserBusiness.getUsers();
}

商业

public List<User> getUsers(){
    return _userDao.findAll();
}

DAO

public List<User> getUsers(){
    try{
        String query = "";
        PreparedStatement ps = null;
        //Query to DB here
    }catch(SQLException e){
    }
}

型号

public class User{
    private int id;
    private String username;
    private String password;
    private String fullName;
}

我的properties文件存放在com.resources包下的Services工程中,com.service包中的classApplicationConfig工程里面包含这个

public static final String PROPERTIES_FILE = "config.properties";
public static Properties properties = new Properties();

private Properties readProperties() {
    InputStream inputStream = getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE);
    if (inputStream != null) {
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            logger.severe(e.getMessage());
        }
    }
    return properties;
}

问题

我的 Services 项目包含项目 Models 作为依赖项。

我需要在我的 DAO 项目中检索一个 属性 值(也许稍后在其他项目中)。我无法将项目 Services 添加到我的 DAO 项目,因为它会添加循环依赖项。因此我无法到达 ApplicationConfig.properties.getProperty("myprop").

如何使用 属性 文件?我应该让 readProperties() 进入 ApplicationConfig 吗?我应该将属性文件放在哪些项目中?

理想情况下,您的 DAO 项目不应依赖与服务项目相同的文件进行配置。您有 2 个选择:

  • 将服务项目中的所有配置一次加载到 class 中。在这种情况下,您最终会得到一个包含所有项目配置的大配置文件。

  • 在单独项目中的 util class 中的静态方法中重用配置文件加载程序代码。每个项目现在都可以拥有自己的配置文件,并依赖于 util 项目来加载和读取配置文件。

我是在我的 DAO 项目中使用 Singleton 完成的。每个项目我将有 1 config.properties 个 class

public class PropertyHandler {

    private final Logger logger = Logger.getLogger(PropertyHandler.class.getName());

    private static PropertyHandler instance = null;

    private Properties props = null;

    private PropertyHandler() {
        try {
            props = new Properties();
            InputStream  in = PropertyHandler.class.getResourceAsStream("config.properties");
            props.load(in);
            in.close();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Error when loading DAO properties file\n***\n{0}", e.getMessage());
        }

    }

    public static synchronized PropertyHandler getInstance() {
        if (instance == null) {
            instance = new PropertyHandler();
        }
        return instance;
    }

    public String getValue(String propKey) {
        return this.props.getProperty(propKey);
    }

}