我正在尝试在我的 Java Web 应用程序中设置一个 Tomcat 连接池(到 MySQL),同时使用 Spring JDBCTemplate。
这是创建连接池的 Java 类:
@Configuration
public class DataAccessConfiguration {
@Bean(destroyMethod = "close")
public javax.sql.DataSource datasource() {
org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
ds.setDriverClassName("org.h2.Driver");
ds.setUrl("jdbc:h2:java-config");
ds.setUsername("sa");
ds.setPassword("");
ds.setInitialSize(5);
ds.setMaxActive(10);
ds.setMaxIdle(5);
ds.setMinIdle(2);
return ds;
}
@Bean public JdbcOperations tpl() {
return new JdbcTemplate(datasource());
}
}
这就是我获取 ApplicationContext
的方式(例如在 main 方法中):
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
我应该如何在 Beans.xml
文件中定义 DataAccessConfiguration
类,以便 Spring 知道如何使用它?
**
更新:
**
这是实际的配置方法:
public javax.sql.DataSource datasource() {
org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:mysql://localhost:3306/mysql");
p.setDriverClassName("com.mysql.jdbc.Driver");
p.setUsername("root");
p.setPassword("");
p.setJmxEnabled(true);
p.setTestWhileIdle(false);
p.setTestOnBorrow(true);
p.setValidationQuery("SELECT 1");
p.setTestOnReturn(false);
p.setValidationInterval(30000);
p.setTimeBetweenEvictionRunsMillis(30000);
p.setMaxActive(100);
p.setInitialSize(10);
p.setMaxWait(10000);
p.setRemoveAbandonedTimeout(60);
p.setMinEvictableIdleTimeMillis(30000);
p.setMinIdle(10);
p.setLogAbandoned(true);
p.setRemoveAbandoned(true);
p.setJdbcInterceptors(
"org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"+
"org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
ds.setPoolProperties(p);
return ds;
}
你能帮忙重写Beans.xml
吗?
最佳答案
对于传递给 Properties setter 方法的值存在。因此基于 XML 的 bean 定义如下:
<bean name="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource">
<property name="url" value="jdbc:mysql://localhost:3306/mysql"/>
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
....
</bean>
<bean name="tpl" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
关于java - 使用 Spring JDBCTemplate 设置 Tomcat JDBC 连接池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27608928/