如何从 2 个主要方法访问相同的 ClassPathXmlApplicationContext 实例
How to access same ClassPathXmlApplicationContext instance from 2 main methods
我必须为 Spring 中的 运行 作业编写一个 quartz 调度程序。我还必须添加另一个功能来暂停相同的工作。此代码存在于单个独立批处理中。
要触发这两个函数:
1.开始工作
2.暂停作业
我用 main() 编写了 2 classes 来执行。
问题是当我触发 pauseJob 的 main() 时,它会启动不同的 applicationContext 而不是使用同一个。我使用单例模式进行 applicationContext 初始化。
Singleton class 用于 ApplicationContext 初始化
public class AppContext {
private static ApplicationContext INSTANCE = null;
private AppContext() {
}
public static ApplicationContext getIntance() {
if (INSTANCE == null) {
String[] contexts = new String[] {"classpath:/applicationContext.xml"};
INSTANCE = new ClassPathXmlApplicationContext(contexts);
}
return INSTANCE;
}
}
Class 开始作业
public class StartJobQuartzMain {
public static void main(String[] args) throws Exception {
AppContext.getIntance();
}
}
Class 暂停作业
public class PauseJobQuartzMain {
public static void main(String[] args) throws Exception {
((TestPauseJob) AppContext.getIntance().getBean("testPauseJob")).pauseJob();
}
}
请指导我如何在 PauseJobQuartzMain.java 中获取相同的 applicationContext 实例。谢谢
让它成为单例与它无关(它在某种程度上是必需的)......两个'java' main 类将运行相互独立,例如,它们是两个不同的程序,具有自己的 Java 虚拟机,并且无法彼此共享您的应用程序上下文。
你可以使用数据库或外部文件(两者都可以访问)或其他东西来实现这个...
希望这对您有所帮助...
你不能从另一个主 class 做到这一点,因为你 运行 它肯定来自一个新的 JVM。所以他们每个人都有自己的单例。您可以考虑在这两个应用程序之间使用一些共享资源:数据库、文件、最后的 JMS 队列等,或者您可以通过 JMX 调用一些托管操作。但是两个 JVM 不能共享内存,尤其是 Java 个对象,当应用程序上下文是其中之一时。
我必须为 Spring 中的 运行 作业编写一个 quartz 调度程序。我还必须添加另一个功能来暂停相同的工作。此代码存在于单个独立批处理中。
要触发这两个函数: 1.开始工作 2.暂停作业 我用 main() 编写了 2 classes 来执行。
问题是当我触发 pauseJob 的 main() 时,它会启动不同的 applicationContext 而不是使用同一个。我使用单例模式进行 applicationContext 初始化。
Singleton class 用于 ApplicationContext 初始化
public class AppContext { private static ApplicationContext INSTANCE = null; private AppContext() { } public static ApplicationContext getIntance() { if (INSTANCE == null) { String[] contexts = new String[] {"classpath:/applicationContext.xml"}; INSTANCE = new ClassPathXmlApplicationContext(contexts); } return INSTANCE; } }
Class 开始作业
public class StartJobQuartzMain {
public static void main(String[] args) throws Exception { AppContext.getIntance(); } }
Class 暂停作业
public class PauseJobQuartzMain {
public static void main(String[] args) throws Exception { ((TestPauseJob) AppContext.getIntance().getBean("testPauseJob")).pauseJob(); } }
请指导我如何在 PauseJobQuartzMain.java 中获取相同的 applicationContext 实例。谢谢
让它成为单例与它无关(它在某种程度上是必需的)......两个'java' main 类将运行相互独立,例如,它们是两个不同的程序,具有自己的 Java 虚拟机,并且无法彼此共享您的应用程序上下文。
你可以使用数据库或外部文件(两者都可以访问)或其他东西来实现这个...
希望这对您有所帮助...
你不能从另一个主 class 做到这一点,因为你 运行 它肯定来自一个新的 JVM。所以他们每个人都有自己的单例。您可以考虑在这两个应用程序之间使用一些共享资源:数据库、文件、最后的 JMS 队列等,或者您可以通过 JMX 调用一些托管操作。但是两个 JVM 不能共享内存,尤其是 Java 个对象,当应用程序上下文是其中之一时。