java - Set object in application context in spring mvc -
i have utility class want initialize when application starts in spring mvc. implementing initializingbean
. have create object same , save in application scope can access same instance everywhere. not able hold of this.
here try:
public class dashboardinitializer implements initializingbean, applicationcontextaware { private applicationcontext mapplication; @override public void afterpropertiesset() throws exception { initializeconfigurationutil(); configurationutil util = configurationutil.getinstance(); /* save util application scope */ } @override public void setapplicationcontext(applicationcontext papplication) throws beansexception { this.mapplication = papplication; } }
is approach correct or there better way that?
i think need simplify little bit.
you want utility class initialized after application context loaded, want util class in application context?
seems util class has dependency objects configured in application context, , util class in turn dependency of classes in application context.
if can express these dependencies in form of beans (util bean, has dependency beans injected it, , beans need util have util injected them), spring ensure dependencies of util initialized first, util initialized , injected classes need util.
you should not try add initialized context.. not possible.
if cannot express util , dependencies beans, can take approach: 1. configure util bean in application context, add default constructor nothing. object created, not initialized when spring context loaded.
in
applicationcontextaware
implementation have, modifysetapplicationcontext
method. util bean configured earlier context.you can initialize (execute code want execute) util instance, make sure not try reassign bean other instance of util.
hope helps.