在为mongo模板检索jndi时,我收到了ClassCastException。
我的server.xml中有以下上下文标记。
<Context
path="/JavaFormBuilderMongoDB-1.0"
docBase="D:/apache-tomcat-8.5.15/webapps/JavaFormBuilderMongoDB-1.0.war"
reloadable="false"
override="true"
allowLinking="true">
<Resource name="jdbc/testMongodbDS" auth="Container" global="jdbc/testMongodbDS"
type="org.springframework.data.mongodb.core.MongoTemplate"
factory="com.dt.formbuilder.CustomMongoJNDIFactory"
host="localhost" port="27017" db="testmongo" username="" password=""/>
</Context>
在上面的资源中,我使用自定义工厂来检索Mongo Template。在代码中我尝试使用jndi进行检索。用于检索mongo模板的代码段是
public @Bean MongoTemplate mongoTemplate() throws Exception {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
Object object =envCtx.lookup("jdbc/testMongodbDS");
return (MongoTemplate) object;
}//mongoTemplate()
但是在将对象转换为Mongo Template时,我遇到了异常。
org.springframework.jndi.TypeMismatchNamingException: Object of type [class org.springframework.data.mongodb.core.MongoTemplate] available at JNDI location [java:/comp/env/jdbc/testMongodbDS] is not assignable to [org.springframework.data.mongodb.core.MongoTemplate]
at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:182) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:95) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:106) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.jndi.JndiObjectFactoryBean.lookupWithFallback(JndiObjectFactoryBean.java:231) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.jndi.JndiObjectFactoryBean.afterPropertiesSet(JndiObjectFactoryBean.java:217) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]