首页 > 解决方案 > 从 Tomcat 中的 context.xml 中检索资源的方法

问题描述

我想从我的 context.xml 中检索值,我发现了这个代码片段:

  // Acquire an instance of our specified bean class
  MyBean bean = new MyBean();

  // Customize the bean properties from our attributes
  Reference ref = (Reference) obj;
  Enumeration addrs = ref.getAll();
  while (addrs.hasMoreElements()) {
      RefAddr addr = (RefAddr) addrs.nextElement();
      String name = addr.getType();
      String value = (String) addr.getContent();
      if (name.equals("foo")) {
          bean.setFoo(value);
      } else if (name.equals("bar")) {
          try {
              bean.setBar(Integer.parseInt(value));
          } catch (NumberFormatException e) {
              throw new NamingException("Invalid 'bar' value " + value);
          }
      }
  }

  // Return the customized instance
  return (bean);

我想知道是否有一种方法可以做同样的事情但步骤更少

标签: javatomcatresourcescontext.xml

解决方案


Tomcat 8.0 上的 Web 应用程序

  1. Tomcat 8.0 的生命周期已结束。不要使用它。请参阅 tomcat.apache.org 上的“迁移指南”以升级到 Tomcat 8.5 或 9.0。

  2. 请参阅 Tomcat 文档中的“ JDNI 资源”。例如factory="org.apache.naming.factory.BeanFactory",可用于创建任意 bean。

  3. 如果您只需要一组可配置的属性,使用Context中的“参数”元素定义它们会更容易。Web 应用程序将通过javax.servlet.ServletContext.getInitParameter(name)API 获取这些值。


推荐阅读