Tomcat のグローバルな JNDI リソースの設定方法です。
- Debian jessie 8.5
- tomcatstack-8.0.36-2-linux-x64
server.xml
の GlobalNamingResources
要素にリソースを追加します。
グローバル定義することで、複数のコンテキストから使用することが可能です。
$ sudo vi /opt/tomcatstack-8.0.36-2/apache-tomcat/conf/server.xml
<Server port="8005" shutdown="SHUTDOWN">
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource name="UserDatabase" auth="Container" type="org.apache.catalina.UserDatabase" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" pathname="conf/tomcat-users.xml"/>
<!-- Additional Resources -->
<Resource name="jdbc/hoge"
global="jdbc/hoge"
auth="Container"
type="javax.sql.DataSource"
url="jdbc:mysql://localhost:3306/databasename"
driverClassName="com.mysql.jdbc.Driver"
username="XXXXXX"
password="XXXXXX"
maxTotal="100"
maxIdle="20"
minIdle="5"
maxWaitMillis="15000"
/>
</GlobalNamingResources>
</Server>
context.xml
に ResourceLink
要素を追加します。
$ sudo vi /opt/tomcatstack-8.0.36-2/apache-tomcat/conf/context.xml
<Context>
<!-- Default set of monitored resources. If one of these changes, the -->
<!-- web application will be reloaded. -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
<!-- Additional resource link -->
<ResourceLink name="jdbc/hoge" global="jdbc/hoge" auth="Container" type="javax.sql.DataSource" />
</Context>
必要に応じてコンテナの lib
ディレクトリに JDBC driver を追加します。
Bitnami Tomcat Stack の場合は、予め PostgreSQL と MySQL の JDBC driver が配備されています。
Spring Framework から使用する場合の Bean の定義方法です。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<!-- DataSource Configuration -->
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/hoge"/>
</bean>
</beans>
直接使用する場合は、web.xml
にリソースの参照設定を追加します。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<resource-ref>
<res-ref-name>jdbc/hoge</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>