java - Spring's application context available everywhere - Set application context in a static variable -


instead of "struggling" inject or pass common spring beans everywhere needed, in non spring managed class, practice set spring's application context in static variable anywhere ? doing allow example jdbctemplate singleton in non spring managed class (or hibernate session factory). there reason not doing ?

for example :

@component public class springcontext implements applicationcontextaware {      private static applicationcontext applicationcontext;      @override     public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception {         springcontext.applicationcontext = applicationcontext;     }      public static jdbctemplate getjdbctemplate() {         return applicationcontext.getbean(jdbctemplate.class);     }      public static sessionfactory getsessionfactory() {         return applicationcontext.getbean(sessionfactory.class);     }      public static session getcurrentsession() {         sessionfactory sf = applicationcontext.getbean(sessionfactory.class);         return sf.getcurrentsession();     }  } 

in class, not managed spring :

public class myclass {      public integer method1() {         string sql = "select 1 dual";         integer n = springcontext.getjdbctemplate().queryforobject(sql, integer.class);         return n;     }  } 

this seems counter spring's intended usage, , concept of dependency injection. whilst this, think better solution inject beans required.

i find practice initialise context once, reference 'root' bean, , bean application , contain references (directly or indirectly) every other bean in system.


Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -