7

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?

DeejUK
  • 12,891
  • 19
  • 89
  • 169

3 Answers3

9

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!

ring0Nerd
  • 91
  • 1
  • 3
1

If I understand the problem correctly, you can find the solution in Spring documentation Section 4. The IoC container

An example on how to start your app is here - 4.2.2 Instantiating a container

Also have a look at 5.7 Application contexts and Resource paths

Vasyl Keretsman
  • 2,688
  • 2
  • 18
  • 15
0

Not sure about other versions, but in Spring 4:

AbstractApplicationContext ctx = new AnnotationConfigApplicationContext(yourConfig.class);
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56