开发者

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

开发者 https://www.devze.com 2022-12-23 17:49 出处:网络
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

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)

开发者_StackOverflow中文版

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?


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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号