如何通过硬编码在web.xml中使用jndi设置?

时间:2015-01-09 15:56:37

标签: java spring tomcat jndi

此属性必须位于web.xml

<resource-ref>
      <description>DB Connection</description>
      <res-ref-name>jdbc/cms</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
    </resource-ref>

如何通过注释硬编码在web.xml中使用jndi设置?

1 个答案:

答案 0 :(得分:0)

我在此假设您已在context.xml中配置了JNDI连接。假设你有,那么答案就像声明一个DataSource字段并使用引用@Resource JNDI名称的jdbc/cms注释来注释它一样简单。像这样:

public class DataSourceFoobar {
    @Resource(name = "jdbc/cms")
    DataSource ds;

    public void doStuff() {
        ds.getConnection(); //etc
        // etc ...
    }
}

如果您还没有在context.xml中配置它,则需要声明一个包含所有必要参数的<Resource />。也许是这样的:

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