1.Spring的配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="jdbc.properties" />
</bean>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>icreate.piis.model.Student</value>
<value>icreate.piis.model.Log</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
</props>
</property>
</bean>
<!-- <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:annotation-driven
transaction-manager="txManager" /> -->
<bean id="studentDAO" class="icreate.piis.service.StudentDAO" />
</beans>
2.通过getBean()可以正确获取sessionFactory
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"beans.xml");
SessionFactory sessionFactory = (SessionFactory) ctx.getBean("sessionFactory");
System.out.println(sessionFactory.getClass());
3.通过注解获取到的是null
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory()
{return sessionFactory;}
@Resource(name="sessionFactory")
public void setSessionFactory(SessionFactory sessionFactory)
{this.sessionFactory = sessionFactory;}
public void addStudent()
{
System.out.println(sessionFactory.getClass()); -->>>出错啦
Session ss = sessionFactory.getCurrentSession();
}
------解决方案--------------------
楼主没启用注解扫描
<context:component-scan base-package="icreate.piis" />
------解决方案--------------------
楼上正解,未引入注解扫描