使用Spring设计Java库 [英] Designing a Java library with Spring

查看:127
本文介绍了使用Spring设计Java库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从现有程序中将一些功能提取到一个单独的库中。
这个程序使用Spring进行依赖注入和其他任务,我也想继续在库中使用它。

I am extracting some functionality from an existing program into a separate library. This program uses Spring for dependency injection and other tasks and I'd like to keep using it in the library as well.

这个库需要监视文件系统进行更改,因此它将启动某种单独的线程来执行此操作。

This library needs to monitor the filesystem for changes, so it will kick off some kind of separate thread to do this.

我真的不知道我的选项是用于初始化库:

I don't really know what my options are for initialisation of the library:


  • 如何初始化库的上下文?我不能假设库用户也会使用Spring,但我可以使用库分发Spring。

  • How do I initialise the library's context? I cannot assume that library users will make use of Spring too, but I can distribute Spring with the library.

如何管理我的文件系统监控线程?期望程序实例化库的主类和调用init或类似的东西是好的设计吗?

How do I manage my filesystem monitoring thread? Is it good design to expect the program to instantiate a main class of the library and the call init or something like that?

推荐答案


如何初始化库的上下文?我不能假设库用户也会使用Spring,但我可以使用库分发Spring。

How do I initialise the library's context? I cannot assume that library users will make use of Spring too, but I can distribute Spring with the library.

这取决于您的库以你需要的方式实例化spring。这通常在您的接口入口点中完成,该入口点使用例如 ClassPathXmlApplicationContext 委托给例程以配置spring。示例可以是

It's up to your library to instantiate spring the way you need it. This is typically done in your interface entrypoint which delegates to a routine using e.g., ClassPathXmlApplicationContext to configure spring. A sample could be

public class SpringContextLoader {
   private static ApplicationContext ctx = null;
   public static void init() {
       if (ctx == null) {
          ctx = ClassPathXmlApplicationContext("classpath:/applicatonContext.xml");
       }
   }
}




如何管理我的文件系统监控线程?期望程序实例化库的主类和调用init或类似的东西是好的设计吗?

How do I manage my filesystem monitoring thread? Is it good design to expect the program to instantiate a main class of the library and the call init or something like that?

在此例如,你可能会提供一个非守护程序线程,例如,一个必须手动终止的线程,以便应用程序干净地退出。因此,您应该提供 start stop 机制。在你的情况下,这些可能更好地称为 registerEventListener unregisterAllEventListener (因为我猜你要传递文件系统事件到客户端 ... )。另一种选择可能是使用 quartz 使用spring安排。

In this case you will probably provide a non-daemon thread, e.g., a thread which must be terminated manually for the application to exit cleanly. Hence you should provide start and stop mechanisms. In your case these probably better be called registerEventListener and unregisterAllEventListener (since I'm guessing you want to pass filesystem events to the client ... ). Another alternative could be to use quartz scheduling with spring.

这篇关于使用Spring设计Java库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆