In Spring/Tomcat, which configuration file do jndi

2019-06-04 06:55发布

问题:

I'm having trouble getting a Spring/Tomcat app to resolve a variable which appears as a property of a JndiFactoryObjectName bean in the application context. Here's the relevant bean entry:

When I try to run it on the server, it comes up with this error:

Caused by: javax.naming.NameNotFoundException: Name search.url is not bound in this Context

This entry in server.xml doesn't seem to help:

There's also an entry in (as seen from Eclipse/STS)

Tomcat v6.0 Server at localhost
   Catalina
     localhost
         ROOT.xml

<Context path="" reloadable="true" docBase="C:/myworkspace32/myAppName/WebContent">
        <ResourceLink global="search.url" name="search.url" type="java.lang.String"/>
</Context>

However, this seem to have no impact.

回答1:

Here are the steps to access JNDI resource from tomcat

  1. Create jndi resource in server.xml

    <Resource global="search.url" name="search.url" type="java.lang.String" />
    
  2. Create the link in context.xml so that its accessible by all the web application.

    <ResourceLink name="search.url"  global="search.url" auth="Container" type="java.lang.String" />
    
  3. Use spring bean or jee tag to inject the jndi

    <bean id="searchUrl" class="org.springframework.jndi.JndiObjectFactoryBean">
     <property name="jndiName" value="java:comp/env/search.url"/>
    </bean>
    

    you can avoid specify the environment by using jee contatiner tag as follows

     <jee:jndi-lookup id="searchUrl" jndi-name="search.url" expected-type="java.lang.String" />
    


回答2:

Follow an example of Tomcat JNDI with Spring

Spring configuration

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">


<jee:jndi-lookup id="yourDS" jndi-name="java:comp/env/yourDS"/>

Tomcat configuration (put this in ${catalina.home}\conf\context.xml)

    <Resource
    name="yourDS"
    type="javax.sql.DataSource"
    username="****"
    password="*****"
    driverClassName="com.ibm.db2.jcc.DB2Driver"  
    url="*******"
    maxActive="8"
    maxIdle="4"
    />