这是我的file.XML,我尝试实例化我的bean: applicationDaoContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
<bean id="EmployeDAO" class="org.o7planning.impl.EmployeDAOImpl">
<property name="sessionFactory" ref="SessionFactory" />
</bean>
</beans> `
这是我的Class EmployeDaooImpl无法实例化:( hibernate spring maven tomcat server)with eclipse
package org.o7planning.impl;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.o7planning.dao.EmployeDao;
import org.o7planning.Entity.Employe;
import org.hibernate.Query;
import org.hibernate.cfg.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public class EmployeDAOImpl implements EmployeDao {
public EmployeDAOImpl() {
super();
}
public void init(){
new EmployeDAOImpl();
System.out.println(" mossab method initi de la classe employimpldao");
}
private SessionFactory sessionFactory;
Session session = sessionFactory.getCurrentSession();
// methode implementer par l'interface
@SuppressWarnings("unchecked")
public List<Employe> getAllEmploye() {
Session session = this.sessionFactory.getCurrentSession();
List<Employe> list = session.createQuery("from EMPLOYEES").getResultList() ;
session.close();
return list;
}
// method implementer par l'interface
public Integer getMaxEmployeByID() {
Session session = this.sessionFactory.getCurrentSession();
String sql = "Select max(E.EMPLOYEE_ID) from EMPLOYEES E ";
Query query = session.createQuery(sql);
Integer maxEmployId = (Integer) query.uniqueResult();
if (maxEmployId == null) {
return 0;
}
return maxEmployId;
}
// methode implementer par l'interface
public void createEmploy(String nom, String prenom) {
Integer employId = getMaxEmployeByID() + 1;
Employe employ = new Employe();
employ.setId_Employe(employId);
employ.setNom(nom);
employ.setPrenom(prenom);
Session session = this.sessionFactory.getCurrentSession();
session.persist(employ);
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
答案 0 :(得分:0)
您需要更改以下代码:
private SessionFactory sessionFactory;
// Remove this line:
// Session session = sessionFactory.getCurrentSession();
此时,sessionFactory未分配值,因此它为null。当Spring注入值时,它的值不为null。 Spring将调用setSessionFactory方法将值注入sessionFactory字段。
您可以在setSessionFactory方法中编写更多代码。