I’m trying create a connection using Spring 3.2.0 but I get NullPointerException of:
ApplicationContext ctx = new ClassPathXmlApplicationContext("conexao/conexao.xml")
my file conexao.xml is in conexao package. And my xml file is configured as presented:
<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>
It always stop at this like when debugging:
ApplicationContext ctx = new ClassPathXmlApplicationContext("conexao/conexao.xml")
my code:
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;
}
What am I doing wrong?
As far as I can see your class name are different:
and in the xml configuration you have:
you could change xml file to
model.Bancoto correct this problem.Another point already commented by Ivan is the case sensitive names. Since you are requesting bean with name
Bancoyou need to change your bean id toBancotoo.and declaration is:
Try to change just your XML to: