javatomcatresourcescontext.xml

Method to retrieve resources from context.xml in Tomcat


I wanted to retrieve values from my context.xml, and I've found this snippet of code to do so:

  // 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);

I wanted to know if there was a method to do the exact same thing but with less steps


Solution

  • a web application on Tomcat 8.0

    1. Tomcat 8.0 has reached End of Life. Do not use it. See "Migration Guide" at tomcat.apache.org to upgrade to Tomcat 8.5 or 9.0.

    2. See "JDNI Resources" in Tomcat documentation. E.g. factory="org.apache.naming.factory.BeanFactory" can be used to create an arbitrary bean.

    3. If you just need a set of configurable properties, defining them with "Parameter" element in Context will be easier. A web application will get those values via javax.servlet.ServletContext.getInitParameter(name) API.