gpt4 book ai didi

java - Spring ClassPathXmlApplicationContext 数据连接

转载 作者:行者123 更新时间:2023-12-01 15:11:12 26 4
gpt4 key购买 nike

我正在尝试使用 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;
}

我做错了什么?

最佳答案

据我所知,您的类(class)名称不同:

import model.Banco;

并且在 xml 配置中您有:

<bean id="banco" class="modelo.Banco">

您可以将 xml 文件更改为 model.Banco 来纠正此问题。

Ivan 已经评论过的另一点是区分大小写的名称。由于您正在请求名为 Banco 的 bean,因此您还需要将 bean id 更改为 Banco

banco = (Banco) ctx.getBean("Banco"); // here your request it with upper B

声明是:

<bean id="banco" class="modelo.Banco">

尝试将您的 XML 更改为:

<bean id="Banco" class="modelo.Banco">

关于java - Spring ClassPathXmlApplicationContext 数据连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12338823/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com