使用Spring设计Java库

Ike*_*nez 24 java spring

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

这个库需要监视文件系统的变化,因此它会启动某种单独的线程来执行此操作.

我真的不知道我对库的初始化有什么选择:

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

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

Mar*_*ira 10

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

我正在使用Spring上下文编写一个库,我做了类似的事情,假设您的库名为FooLib,有两个名为FooServiceBarService的服务,以及一个名为SpringContext的类,它通过java配置配置您的spring上下文:

public final class FooLib {

    private static ApplicationContext applicationContext;

    private FooLib() {
    }

    public static FooService getFooService() {
        return getApplicationContext().getBean(FooService.class);
    }

    public static BarService getBarService() {
        return getApplicationContext().getBean(BarService.class);
    }

    private static ApplicationContext getApplicationContext() {
        if (applicationContext == null) {
            applicationContext = new AnnotationConfigApplicationContext(SpringContext.class);
        }
        return applicationContext;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后客户端可以使用BarService这种方式:

BarService barService = FooLib.getBarService();
Run Code Online (Sandbox Code Playgroud)

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

例如,您可以在SpringContext类的Spring上下文中静态启动监视子系统.

@Configuration
@ComponentScan(basePackages = "com.yourgroupid.foolib")
public class SpringContext {

    @Bean
    public MonitoringSystem monitoringSystem() {
        MonitoringSystem monitoringSystem = new MonitoringSystem();
        monitoringSystem.start();
        return monitoringSystem;
    }

}
Run Code Online (Sandbox Code Playgroud)

这应该足够了,因为Spring默认会急切地创建它的bean.

干杯


Joh*_*erg 8

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

这取决于您的库,以您需要的方式实例化spring.这通常在您的接口入口点完成,该入口点使用例如ClassPathXmlApplicationContext配置弹簧来委托例程.样本可以是

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

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

在这种情况下,您可能会提供一个非守护程序线程,例如,一个必须手动终止的线程,以便应用程序干净地退出.因此,你应该提供startstop机制.在你的情况下,这些可能是更好的被称为registerEventListenerunregisterAllEventListener(因为我猜你想通过文件系统事件给客户...).另一种选择可以是使用quartzspring 进行调度.