我正在使用spring jdbc進行數據庫連接。每次運行我的測試java類spring時,上下文也會每次加載。任何建議?爲什麼每次都加載spring應用上下文
我的代碼片斷低於,
appContext.xml:
<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/beans/spring-context-2.0.xsd ">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/3i" />
<property name="username" value="xxx" />
<property name="password" value="xxx" />
</bean>
<bean id="jdbcTemp" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource">
</property>
</bean>
</beans>
Java類:
package com.pinovus.dbconnection;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
public class DbDao {
private static JdbcTemplate jdbctemplate;
private static ApplicationContext appcontext;
public JdbcTemplate getJdbctemplate() {
ApplicationContext cx = new ClassPathXmlApplicationContext(
"appContext.xml");
jdbctemplate = (JdbcTemplate) cx.getBean("jdbcTemp");
return jdbctemplate;
}
public void setJdbctemplate(JdbcTemplate jdbctemplate) {
this.jdbctemplate = jdbctemplate;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
和測試Java類:
package com.pinovus.dbconnection;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
JdbcTemplate jt = new DbDao().getJdbctemplate();
String qry = "select role from accounts";
SqlRowSet rs = jt.queryForRowSet(qry);
while (rs.next()) {
System.out.println(rs.getString(1));
}
}
}
您正在調用每次加載spring上下文的'getJdbctemplate()'。你想要它做什麼? – jervine10
現在我明白了它的代碼問題,每次我調用getJdbctemplate()方法 – jasim