我尝试使用 Hibernate 4.1.6 和 Spring 3.0.5 创建一个 Java 程序。当我运行我的应用程序时抛出 NULLPOINT 异常。请任何人帮助我,
SpringBeans.xml:
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<!-- Database Configuration --> <import resource="config/spring/DataSource.xml"/> <import resource="config/spring/HibernateSessionFactory.xml"/> <!-- Beans Declaration --> <import resource="config/spring/UserBeans.xml"/>
2. HibernateSessionFactory.xml
<property name="dataSource"> <ref bean="dataSource"/> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> <property name="mappingResources"> <list> <value>com/model/TblUser.hbm.xml</value> </list> </property>
DataSource.xml
WEB-INF/classes/config/database/properties/database.properties
数据库.属性
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql:localhost:3306/auction_nms jdbc.用户名=root jdbc.password=root
UserBeans.xml
<!-- User business object -->
UserDaoImpl.java
公共(public)类 UserDaoImpl 实现 UserDao { @Autowired SessionFactory sessionFactory;
/* * @see com.dao.UserDao#save(com.model.TblUser) */ @Override public void save(TblUser user) { sessionFactory.getCurrentSession().save(user); }
7.App.java
public class App {
// get log4j handler
private static final Logger logger = Logger.getLogger(App.class);
static TblUser user = new TblUser(2, "2", "2");
public static void main(String[] args) {
try {
UserDao userDao = new UserDaoImpl();
userDao.save(user);
} catch (Exception e) {
System.err.`enter code here`println(e);
} finally {
if (logger.isDebugEnabled()) {
logger.debug(user);
}
}
}
}
非常感谢!!!
最佳答案
您正在使用 new
关键字创建 UserDAO
对象。您应该通过加载 appContext 来启动 spring 容器,在您的例子中是 SpringBeans.xml
。
如果您使用 new 关键字 Spring 不会管理您的依赖项,因此您的 sessionFactory 永远不会注入(inject)到 DAO 实例中。
这应该是您的 main()
的内容,而不是当前的内容。
ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] {
"classpath*:/META-INF/SpringBeans.xml"
});
appContext.getBean("userDao");
..调用你的保存即可。
关于java - NullPointEreException 与 Hibernate 4 和 Spring 3.0.5 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21181431/