Tiven Wang
Wang Tiven November 23, 2017
425 favorite favorites
bookmark bookmark
share share

https://stackoverflow.com/questions/9183321/how-to-use-jndi-datasource-provided-by-tomcat-in-spring

https://stackoverflow.com/questions/5940895/how-to-test-a-mocked-jndi-datasource-with-spring

https://tomcat.apache.org/tomcat-7.0-doc/jndi-datasource-examples-howto.html

Adding Custom Resource Factories

通过实现 javax.naming.spi.ObjectFactory 接口,并把其配置在Context里:

<Context ...>
  ...
  <Resource name="bean/MyBeanFactory" auth="Container"
            type="com.mycompany.MyBean"
            factory="com.mycompany.MyBeanFactory"
            singleton="false"
            bar="23"/>
  ...
</Context>

详细参见 https://tomcat.apache.org/tomcat-7.0-doc/jndi-resources-howto.html#Adding_Custom_Resource_Factories

List All Resources

如果你获取不到 Resource, 可以通过输出全部的信息来 Debug:

public static Map toMap(Context ctx) throws NamingException {
  String namespace = ctx instanceof InitialContext ? ctx.getNameInNamespace() : "";
  HashMap<String, Object> map = new HashMap<String, Object>();

  NamingEnumeration<NameClassPair> list = ctx.list(namespace);
  while (list.hasMoreElements()) {
    NameClassPair next = list.next();
    String name = next.getName();
    String jndiPath = namespace + name;
    Object lookup;
    try {
      Object tmp = ctx.lookup(jndiPath);
      if (tmp instanceof Context) {
        lookup = toMap((Context) tmp);
      } else {
        lookup = tmp.toString();
      }
    } catch (Throwable t) {
      lookup = t.getMessage();
    }
    map.put(name, lookup);
  }
  return map;
}

// Print the Context to JSON string
System.out.println(new ObjectMapper().writeValueAsString(this.toMap(envCtx)));

或者只打印变量名:

InitialContext ctx = new InitialContext();
NamingEnumeration<NameClassPair> list = ctx.list("");
while (list.hasMore()) {
  System.out.println(list.next().getName());
}

Comments

comments powered by Disqus
Back to Top