嵌入式tomcat jndi定义

时间:2016-02-07 16:50:55

标签: java spring tomcat embedded-tomcat-7

我使用嵌入式tomcat的spring。我不想再使用application.properties了,因为它应该发布到运行tomcat的web服务器上,现在我正在使用来自context.xml的JNDI dataSource,它运行得非常好。现在我想为嵌入式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>

Configuration.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].

请帮助我,谢谢:)

1 个答案:

答案 0 :(得分:0)

尝试

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

没有java:comp,找不到jndi。&#34; comp&#34;是组件的缩写,并且绑定到根上下文。