how use jndi settings in web.xml via hard coding?

2019-09-01 18:49发布

there is this property which must be in 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>

how use jndi settings in web.xml via hard coding by annotation?

1条回答
别忘想泡老子
2楼-- · 2019-09-01 19:29

I'm assuming here that you have configured the JNDI connection in context.xml. Assuming you have, then the answer is as simple as declaring a DataSource field and annotating it with an @Resource annotation that refers to your jdbc/cms JNDI name. Like so:

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

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

Configuring it in the context.xml, if you haven't already, involves declaring a <Resource /> with all the necessary parameters. Maybe like this:

<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"/>
查看更多
登录 后发表回答