tags:

views:

39

answers:

3

I'm looking for an example which shows how to instantiate a Spring container within the context of a set of classes packaged in a plain old, non-executable java library/JAR. The core purpose here is provide dependency injection (primarily for logging)

The fundamental problem as I see it is that a non-executable jar has no single startup point - no main method. So how do I go about creating and configuring the necessary application context?

Thanks in advance,

-steve

A: 

Apache CXF contains code for this. However, to be honest, it's about 5 lines of code.

bmargulies
A: 

Well your framework has to provide the necessary starting point somehow of course, e.g. a factory method that the user of your library has to call somewhere. An alternative would be to use a static block which will be executed as soon as the class has been loaded, e.g.:

public class BootStrap
{
    private static final ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

    public static ApplicationContext getContext()
    {
        return context;
    }

    private BootStrap() {}
}
Daff
Thanks. Unless I'm missing something, the static block is what I was looking for. I'll give it a try.
Steve N
+2  A: 

See the Spring chapter on "Glue Code and The Evil Singleton". This describes how to bootstrap Spring in cases where it's not provided as part of a container lifecycle, using ContextSingletonBeanFactoryLocator. Spring will handle the distasteful process of maintaining a singleton reference to the context, which your JAR code can access at its leisure. No entry point or startup routines required, it's performed lazily on demand.

skaffman
This http://book.javanb.com/Professional-Java-Development-with-the-Spring-Framework/BBL0090.html article provided an example and helped fill out the info from above
Steve N