我尝试使用Hibernate 4.1.6和Spring 3.0.5创建Java程序。当我运行我的应用程序时抛出NULLPOINT EXCEPTION。任何人都可以帮助我,
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 /班/配置/数据库/属性/ database.properties
database.properties
jdbc.driverClassName = com.mysql.jdbc.Driver jdbc.url = JDBC:MySQL的:本地主机:3306 / auction_nms jdbc.username =根 jdbc.password =根
UserBeans.xml
<!-- User business object -->
UserDaoImpl .java
public class 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);
}
}
}
}
非常感谢!!!
答案 0 :(得分:3)
您正在使用UserDAO
关键字创建new
对象。您应该通过加载appContext来启动spring容器,在您的情况SpringBeans.xml
中。
如果您使用new
关键字Spring并不管理您的依赖项,那么,您的sessionFactory
永远不会注入DAO实例。
这应该是您main()
的内容,而不是当前的内容。
ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] {
"classpath*:/META-INF/SpringBeans.xml"
});
appContext.getBean("userDao");
..打电话给你保存。