Obtaining factory null in spring SessionFactory with Resource configured

5

The class name containing SessionFactory is DataProvider and has the following implementation:

@Resource(name="sessionFactory")
protected SessionFactory factory;

protected Class<E> entity;
protected String tableName;

public DataProvider(Class e) {
   this.entity = e;
   this.tableName = entity.getAnnotation(Table.class).name();
}

@Transactional(readOnly = true)
public List<E> getAll() {
    Session s = factory.getCurrentSession(); // A exceção acontece aqui.
    return s.createQuery("FROM " + tableName ).list();
}

The bean with the SessionFactory setting is:

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="models"/>
    <property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
        </props>
    </property>
</bean>

I'm getting NullPointerException on the commented line. The question is: am I doing something wrong or is there still some configuration?

    
asked by anonymous 18.02.2014 / 18:39

1 answer

2

For Spring to resolve dependencies using annotations, you need to add an extra setting in your applicationContext.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"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <context:annotation-config/>

<context:component-scan base-package="br.com.meupacote." />

<!-- seus outros beans -->


</beans>

The <context:annotation-config/> setting tells Spring that it must resolve dependencies indicated by annotations (either @Resouce, @Autowired or @Inject), the <context:component-scan base-package="br.com.meupacote" /> setting tells Spring to look for these dependencies in classes that belong to the br.com.meupacote.* package.

In addition, for Spring to resolve dependencies in its DataProvider class, this class must belong to the Spring context. An easy way to set this is to annotate it with @Component. Example:

@Component
public class DataProvider{
 // ....
} 

Version 3.0.0 documentation: link

    
21.02.2014 / 03:05