java - 嵌入式tomcat jndi定义

标签 java spring tomcat embedded-tomcat-7

我正在使用带有嵌入式 tomcat 的 spring。我不想再使用 application.properties,因为它应该发布到运行 tomcat 的网络服务器,而我现在正在使用来自 context.xml 的 JNDI 数据源,它工作得很好。现在我想为嵌入式 tomcat 定义 JNDI 资源,但它不起作用。

我尝试过的:

context.xml

<?xml version='1.0' encoding='utf-8'?>

<Context>

    <Resource name="jdbc/db" auth="Container" type="javax.sql.DataSource"
        maxActive="100" maxIdle="30" maxWait="10000"
        username="root" password="root" driverClassName="com.mysql.jdbc.Driver"
        url="jdbc:mysql://localhost:3306/db"/>

</Context>

配置.java

@Bean
public DataSource dataSource() {
    final JndiDataSourceLookup lookup = new JndiDataSourceLookup();
    lookup.setResourceRef(true);
    return lookup.getDataSource("jdbc/db");
}

@Bean
public TomcatEmbeddedServletContainerFactory tomcatFactory() {
    return new TomcatEmbeddedServletContainerFactory() {
        @Override
        protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(Tomcat tomcat) {
            tomcat.enableNaming();
            return super.getTomcatEmbeddedServletContainer(tomcat);
        }
    };
}

我得到:

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]:
Factory method 'dataSource' threw exception; nested exception is org.springframework.jdbc.datasource.lookup.DataSourceLookupFailureException: Failed to look up JNDI DataSource with name 'jdbc/db';
nested exception is javax.naming.NameNotFoundException: Name [jdbc/db] is not bound in this Context. Unable to find [jdbc].

请帮助我,谢谢:)

最佳答案

试试

lookup.getDataSource("java:/comp/env/jdbc/db");

没有java:comp,找不到jndi。“comp”是component的缩写,绑定(bind)到root context。

关于java - 嵌入式tomcat jndi定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35256256/

相关文章:

Java,与对象关联的变量是否持久存在?大整数示例

java - HIVE:NoSuchMethodError:org.fusesource.jansi.internal.Kernel32.GetConsoleOutputCP()I

eclipse - 如何向 Eclipse 添加更多服务器类型选项?

java - 如何在 Spring XML 文件中声明 Java 8 方法引用?

jsp - JspServlet中的 "mappedfile"参数代表什么?

Apache 代理到 Tomcat 强制 SSL

java - Eclipselink 忽略 persistence.xml 中的属性 javax.persistence.jdbc.driver 和 javax.persistence.jdbc.url

java - 不序列化基于值的类(例如 LocalDateTime)的替代方案是什么

java - @Value boolean 返回值 true 的 'invalid boolean value'

java - 在 Spring MVC 应用程序中将 DAO 对象转换为 DTO 对象