在servlet外部检索Init参数

我有一个我必须修改的3层应用程序。 我对Java的整个网络都很陌生,所以请耐心等待。

目前,该应用程序具有UI,应用程序和数据库层,但我试图使用dependency injection将SQL数据库与数据库层分离。

所以在某些时候我不会在我的应用程序中需要SQL服务器凭据,因为数据库后端可能是纯文本。

关键是当前的SQL凭据作为init-parameters存储在web.xml文件中。 这些是在servlet代码中获取的,如下所示:

String cfgfile = getInitParameter("config_file"); properties.load(new FileInputStream(cfgfile)); //Some code.. properties.getProperty("dbUser"); 

这发生在前端,传递给applicationlayer构造函数,后者将其传递给数据库构造函数。

所以这可行,但凭据只是传递到数据访问层,然后创建一个SQLDatabase。

所以我想我只是在SQL特定类中提取这些凭据。 但是,我仍然坚持如何将它们从web.xml文件中删除。

我尝试使用getServletContext()但似乎没有用。

我可以想象在DAL级别没有任何servlet的概念,所以我坚持如何解决这个问题。

注册ServletContextListener以在服务器启动时加载Init参数。

加载属性并使其对其他类静态可见。

示例代码:

 public class AppServletContextListener implements ServletContextListener { private static Properties properties; @Override public void contextInitialized(ServletContextEvent servletContextEvent) { String cfgfile = servletContextEvent.getServletContext().getInitParameter("config_file"); properties.load(new FileInputStream(cfgfile)); //Some code.. properties.getProperty("dbUser"); } public static Properties getProperties(){ return properties; } } 

web.xml中:

  com.xyzAppServletContextListener   config_file config_file_location  

你是正确的,web.xml似乎是定义数据库凭据的错误位置。

听起来你真的想要将数据库凭证定义为属性并将它们直接注入数据访问层。

在使用Spring时,您可能需要考虑在context.xml定义DataSource,并直接在其中定义凭据或使用属性文件。 有关更多详细信息,请查看Spring文档 。