我正在将现有程序中的一些功能提取到一个单独的库中。
该程序使用 Spring 进行依赖注入和其他任务,我也想继续在库中使用它。
该库需要监视文件系统的更改,因此它将启动某种单独的线程来执行此操作。
我真的不知道我的库初始化选项是什么:
如何初始化库的上下文?我不能假设
库用户也会使用 Spring,但我可以分发 Spring
与图书馆。
我也在使用 Spring 上下文编写一个库,我做了类似的事情,假设你的库被称为FooLib,有两个服务称为食品服务 and 酒吧服务和一个名为 SpringContext 的类,它通过 java config 配置你的 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;
}
}
然后客户端可以使用BarService
这边走:
BarService barService = FooLib.getBarService();
如何管理我的文件系统监控线程?是不是好的设计
期望程序实例化库的主类和
调用 init 或者类似的东西?
您可以在 Spring 上下文中静态启动监控子系统,例如在 SpringContext 类中。
@Configuration
@ComponentScan(basePackages = "com.yourgroupid.foolib")
public class SpringContext {
@Bean
public MonitoringSystem monitoringSystem() {
MonitoringSystem monitoringSystem = new MonitoringSystem();
monitoringSystem.start();
return monitoringSystem;
}
}
这应该足够了,因为 Spring 默认情况下会急切地创建它的 bean。
Cheers
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)