Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ApplicationContextInitializer in a non-web Spring Context?

I've created an ApplicationContextInitializer implementation to load properties from a custome source (ZooKeeper) and add them to the ApplicationContext's property sources list.

All the documentation I can find relates to Spring web-apps, but I want to use this in a standalone message-consuming application.

Is the right approach to instantiate my implementation, create the context, then pass the context to my implementation 'manually'? Or am I missing some automatic feature fo the framework that will apply my initializer to my context?

like image 638
EngineerBetter_DJ Avatar asked Nov 08 '12 12:11

EngineerBetter_DJ


People also ask

What is spring boot ApplicationContextInitializer?

Now, what is an ApplicationContextInitializer. It is essentially code that gets executed before the Spring application context gets completely created.

Can we have multiple application context in Spring?

We can have multiple application contexts that share a parent-child relationship. A context hierarchy allows multiple child contexts to share beans which reside in the parent context. Each child context can override configuration inherited from the parent context.

How do I get Springapplication context?

To get a reference to the ApplicationContext in a Spring application, it can easily be achieved by implementing the ApplicationContextAware interface. Spring will automatically detect this interface and inject a reference to the ApplicationContext: view rawMyBeanImpl. java hosted by GitHub.

Which context holds the ServletContext information in Spring web applications?

WebApplicationContext in Spring is a web-aware ApplicationContext i.e it has Servlet Context information. In a single web application, there can be multiple WebApplicationContext.


1 Answers

I have found it simple enough to implement the SpringMVC's strategy for Initializing a context by initializing with a blank context. In normal application contexts, there is nothing which uses an ApplicationContextInitializer, thus you must execute it on your own.

No problem, though since within a normal J2SE application given you have ownership of the context loader block, you will have access to every stage of the lifecycle.

// Create context, but dont initialize with configuration by calling 
// the empty constructor. Instead, initialize it with the Context Initializer.
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
MyAppContextInitializer initializer = new MyAppContextInitializer();
initializer.initialize( ctx );

// Now register with your standard context
ctx.register( com.my.classpath.StackOverflowConfiguration.class );
ctx.refresh()

// Get Beans as normal (e.g. Spring Batch)
JobLauncher launcher = context.getBean(JobLauncher.class);

I hope this helps!

like image 91
ring0Nerd Avatar answered Sep 30 '22 15:09

ring0Nerd