我正在尝试使用 Spring 3.2.0 创建连接,但我得到 NullPointerException:
ApplicationContext ctx = new ClassPathXmlApplicationContext("conexao/conexao.xml")
我的文件 conexao.xml 在conexao
包中。我的 xml 文件配置如下:
<beans>
<bean id="banco" class="modelo.Banco">
<property name="usuario">
<value>root</value>
</property>
<property name="senha">
<value>""</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/agenda</value>
</property>
<property name="classForName">
<value>com.mysql.jdbc.Driver</value>
</property>
</bean>
</beans>
它总是在调试时停止:
ApplicationContext ctx = new ClassPathXmlApplicationContext("conexao/conexao.xml")
我的代码:
package dao;
import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import model.Banco;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Conexao {
private static Banco banco;
private static Conexao instance;
public static Conexao getInstance() {
if (Conexao.instance == null) {
Conexao.instance = new Conexao();
}
return Conexao.instance;
}
private Conexao() {
}
public Connection abrirConexao() {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"conexao/conexao.xml");
Connection con = null;
banco = (Banco) ctx.getBean("Banco");
try {
Class.forName(banco.getClassForName()); // Carrega o driver
con = (Connection) DriverManager.getConnection(banco.getUrl(),
banco.getUsuario(), banco.getSenha()); // obtem a conexao
// com o banco
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
return con;
}
public Statement getStatement() throws SQLException, ClassNotFoundException {
return abrirConexao().createStatement();
}
public PreparedStatement getPreparedStatement(String sql)
throws InterruptedException {
PreparedStatement ps = null;
try {
ps = this.abrirConexao().prepareStatement(sql);
} catch (Exception e) {
System.out
.println("Erro com a conexao. Verifique se sua conexao esta ativa.");
}
return ps;
}
我究竟做错了什么?