java - spring singleton object state -


here have 1 doubt spring singleton object.

spring create atleast 1 object per bean definition depending on scope. singleton scope, 1 object per bean definiton.

as spring context provide singleton instance why not able share same session of it.

the below code give error:

throw null pointer error. org.hibernate.transactionexception: transaction not started

while trying access same instance session. session instance 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 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 start session again works.  dao.getsession().saveorupdate(isbean); //throw null pointer error. org.hibernate.transactionexception: transaction not started   }  else  {  dao.saveorupdate(isbean);   }  }  public void startoperation() throws hibernateexception {  session = hibernatefactory.opensession();  transaction = session.begintransaction();  } 

if start session again or pass same session instance in method works fine not understand why not work. singleton instance not have same state in spring context!!

thanks in advance

to use spring must bootstrap depenedency injection container. container can point xml file defining beans or class using springs java configuration. once container bootstrapped manages of beans singletons. code provided uses static method on applicationcontext class never has actual handle instance of applicationcontext meaning no beans defined within it.

here example of bootstrapping via xml:

// create , configure beans applicationcontext context =     new classpathxmlapplicationcontext(new string[] {"services.xml", "daos.xml"}); 

Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -