user300143
user300143

Reputation:

How does one instantiate Spring in the context of a library?

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?

Upvotes: 4

Views: 1662

Answers (3)

skaffman
skaffman

Reputation: 403591

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.

Upvotes: 1

Daff
Daff

Reputation: 44215

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() {}
}

Upvotes: 1

bmargulies
bmargulies

Reputation: 100153

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

Upvotes: 0

Related Questions