你知道是否可以在jndi中通过datasource设置mongodb实例,就像任何其他数据库一样?
谢谢
是的,有可能,为什么在你可以创建自己的JNDI工厂时依赖别人的代码呢?只需创建一个实现javax.naming.spi.ObjectFactory的类和一个从JNDI上下文中提取mongo的bean,我将其配置为spring data-mongo MongoTemplate对象.
public class CustomMongoJNDIFactory implements ObjectFactory { public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable, ?> environment) throws Exception { validateProperty(obj, "Invalid JNDI object reference"); MongoTemplate mongoTemplate = null; String db = null; String host = null; String username = null; String password = null; int port = 27017; Reference ref = (Reference) obj; Enumerationprops = ref.getAll(); while (props.hasMoreElements()) { RefAddr addr = (RefAddr) props.nextElement(); String propName = addr.getType(); String propValue = (String) addr.getContent(); if (propName.equals("db")) { db = propValue; } else if (propName.equals("host")) { host = propValue; } else if (propName.equals("username")) { username = propValue; } else if (propName.equals("password")) { password = propValue; } else if (name.equals("port")) { try { port = Integer.parseInt(propValue); } catch (NumberFormatException e) { throw new NamingException("Invalid port value " + propValue); } } } // validate properties validateProperty(db, "Invalid or empty mongo database name"); validateProperty(host, "Invalid or empty mongo host"); validateProperty(username, "Invalid or empty mongo username"); validateProperty(password, "Invalid or empty mongo password"); //create mongo template mongoTemplate = new MongoTemplate(new Mongo(host, port), db, new UserCredentials(username, password)); return mongoTemplate; } /** * Validate internal String properties * * @param property * @param errorMessage * @throws NamingException */ private void validateProperty(String property, String errorMessage) throws NamingException { if (property == null || property.trim().equals("")) { throw new NamingException(errorMessage); } } /** * Validate internal Object properties * * @param property * @param errorMessage * @throws NamingException */ private void validateProperty(Object property, String errorMessage) throws NamingException { if (property == null) { throw new NamingException(errorMessage); } }
}
春豆:
@Configuration @Qualifier("mongoTemplate") public class CustomMongoTemplate { public @Bean MongoTemplate mongoTemplate() throws Exception { Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); return (MongoTemplate) envCtx.lookup("bean/MyMongoBean"); } }
context.xml中:
在web.xml
Mongo JNDI configuration comp/env/bean/MyMongoBean org.springframework.data.mongodb.core.MongoTemplate