日期:2014-05-18  浏览次数:20961 次

关于注解(@Resource)获取对象为nullPointException的问题
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