0

Follow up to my existing question, I am getting null session factory and hence my transaction is being failed. Here is what my class structure looks like

@Component
public class MyCachingObj extends HibernateMapper{
    @PostConstruct
    public void loadAll() {
        ...
        getCurrentSession().getQuery(); //this method is in HibernateMapper
        ...
    }
}


@Repository
public class HibernateMapper {
    @Autowired
    private SessionFactory _session;

    public Session getCurrentSession() {
        return _session;
    }
}

What I have read so far, that @PostConstruct doesn't guarantee that spring is done with all beans. Then how can i make sure that spring is done processing and i have session ready to be picked up ?

EDIT I ended up creating

@Component
@Transactional
@Repository
public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent>{..}

which had autowired sessions and autowired another Component class. However, i noticed that this onApplicationEvent method was being called twice. I ended up putting a boolean variable to load the underlying data only once.

Now few questions

  1. Why onApplicationEvent is being called twice.
  2. My cached object is annotated with @Component, Is it safe to assume that as long as that object is being used by @Autowired instance, it would remain singleton and would hold the data i loaded at startup ?
Community
  • 1
  • 1
Em Ae
  • 8,167
  • 27
  • 95
  • 162
  • You can create a Listener which is not called until all beans are initialized and add the necessary logic in that. See:http://stackoverflow.com/questions/8686507/how-to-add-a-hook-to-the-application-context-initialization-event and http://docs.spring.io/spring/docs/2.5.x/reference/beans.html#context-functionality-events – Alan Hay Feb 03 '16 at 16:08
  • Yup thats what I did, see updated post ... I have asked new questions in my edit. – Em Ae Feb 03 '16 at 16:11

0 Answers0