【发布时间】:2018-08-10 05:59:34
【问题描述】:
我刚接触 Spring 并面临设计问题。问题是我有一个 Maven 多模块项目。项目结构如下。
模块后台 - 打包(战争)
module-ws - 打包(战争)
module-dao - 打包(jar)
模块共享 - 打包(jar)
在“module shared”中我所有的服务类和在“module-dao”中所有与dao相关的代码都存在。 module-shared 和 module-dao 在 module-backoffice 和 module-ws 的构建路径中。
现在的问题是,当我运行 module-backoffice war 和 module-ws war 时,Spring 创建了两个 Service 类 bean 和 dao 类 bean 的实例。
我应该怎么做才能创建服务类和 dao 类的一个实例并在多个战争之间共享?请帮忙。谢谢你。
Module-Shared 中的代码:下面是服务工厂类
@org.springframework.stereotype.Service
public class Services {
@Autowired
private List<Service> services;
private static final Map<Class<?>, Service> serviceCache = new ConcurrentHashMap<Class<?>, Service>();
@PostConstruct
public void initServiceCache() {
services.forEach(service -> serviceCache.put(service.getClass(), service));
services = null;
}
public static Bootstrap bootstrap() {
return (Bootstrap) serviceCache.get(Bootstrap.class);
}
服务类是:
@Component
public class Bootstrap implements Service {
public Bootstrap() {
System.out.println("Bootstrap");
}
}
当我运行 tomcat 部署两次战争时,然后在控制台中打印两次“Bootstrap”。我该如何限制呢?
【问题讨论】:
-
您如何知道服务正在创建两次?并将您的配置发布到战争文件中。
-
当你运行两个差异战争时,我应该初始化依赖两次。请分享您的配置。
-
请查看我的代码。我已经编辑了
-
您正在部署 2 个应用程序,因此您将获得 2 个 bean 实例。
-
我可以做些什么来共享一个实例
标签: java spring architecture