bNd
bNd

Reputation: 7640

spring singleton object state

Here I have one doubt with spring singleton object.

Spring will create atleast one object per bean definition depending on the scope. for singleton scope, you will get only one object per bean definiton.

As spring context provide us singleton instance then why I am not able to share same session of it.

The below code give error:

Throw null pointer error. org.hibernate.TransactionException: Transaction not successfully started

while trying to access same instance session. even session instance is null.

In main method

public static void main(String[] args)
{
  TestDao dao =  (TestDao) ApplicationContext.getInstance().getBean(DaoType.TestDao.toString());
  dao.startOperation();
  for(Test test:testList)
  {
     saveIsBean(test,true)
  }
  dao.endOperation();
}

This method save data if session open then reuse it.

private void saveIsBean(IsBean isBean,boolean isSessionAlreadyOpen) throws NTException
 {
 TestDao dao =  (TestDao) ApplicationContext.getInstance().getBean(DaoType.TestDao.toString());
  if(isSessionAlreadyOpen)
 {
 //dao.startOperation(); If I start session again then it works.
 dao.getSession().saveOrUpdate(isBean); //Throw null pointer error. org.hibernate.TransactionException: Transaction not successfully started
  }
 else
 {
 dao.saveOrUpdate(isBean);
  }
 } 
public void startOperation() throws HibernateException {
 session = HibernateFactory.openSession();
 transaction = session.beginTransaction();
 }

If I start session again or pass same session instance in method then it works fine but I do not understand why it does not work. singleton instance does not have same state in spring context!!

Thanks In Advance

Upvotes: 2

Views: 1453

Answers (1)

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

To use Spring you must bootstrap the depenedency injection container. The container can point to an xml file defining your beans or a class using Springs Java configuration. Once the container is bootstrapped it manages all of your beans as singletons. The code you provided uses a static method on the ApplicationContext class so it never has an actual handle to an instance of the ApplicationContext meaning no beans are defined within it.

Here is an example of bootstrapping via xml:

// create and configure beans
ApplicationContext context =
    new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});

Upvotes: 1

Related Questions