Java 类的数据结构被其他多个类SpringBoot重用
我是Spring Boot新手,刚刚用HTTP实现了一个普通的Spring Boot应用程序,其中端点接收数据并放入数据库。现在,我希望将一些数据放入数据库和具有数据结构的类中。由于这些数据将有连续的操作,我需要将其作为一个单独的过程进行操作Java 类的数据结构被其他多个类SpringBoot重用,java,spring,spring-boot,Java,Spring,Spring Boot,我是Spring Boot新手,刚刚用HTTP实现了一个普通的Spring Boot应用程序,其中端点接收数据并放入数据库。现在,我希望将一些数据放入数据库和具有数据结构的类中。由于这些数据将有连续的操作,我需要将其作为一个单独的过程进行操作 @Service public class RulesManager { private HashMap<Integer, Rule> rules = new HashMap<Integer, Rule>(); publi
@Service
public class RulesManager {
private HashMap<Integer, Rule> rules = new HashMap<Integer, Rule>();
public void addRule(Rule rule) {
// Add rule to the database
}
// should be running in the background
public void updateRules(){
// Continuous check of rules and update of this.rules HashMap
}
}
@SpringBootApplication
public class RulesApplication {
public static void main(String... args) {
SpringApplication.run(RulesApplication.class, args);
// How do I call RulesManager.updateRules() to run in the background and make changes to rules hashmap???
}
}
@服务
公共类规则管理器{
私有HashMap规则=新建HashMap();
公共无效添加规则(规则){
//将规则添加到数据库
}
//应该在后台运行
公共void updateroles(){
//持续检查规则并更新此.rules HashMap
}
}
@SpringBoot应用程序
公共类规则应用程序{
公共静态void main(字符串…参数){
run(RulesApplication.class,args);
//如何调用RulesManager.updateRules()在后台运行并更改规则hashmap???
}
}
所以,在侦听HTTP请求时,我希望我的应用程序运行后台进程,该进程永远不会停止并重复自身。我不知道如何从主RulesApplication类调用该类,以便http请求和后台进程都能够对this.rules HashMap进行更改。非常感谢您提供的任何提示或建议。如果您只是希望在应用程序启动时启动一个始终开启的流程(在RuleManager初始化时更好),那么您只需在RuleManager的构造函数中创建一个新线程:
methodCalledByConstructor()
{
new Thread(()->{
// loop start
// access and check the hashmap
// do what is necessary
// sleep for a sometime
// loop end
}).start();
}
但是,如果只在某些事件发生时才需要进行此项工作,则使用观察器模式来获得更优雅的解决方案。尝试定义一个新线程,例如“LocalRulesHandling”,并用@Component对其进行注释,并在该线程中添加与规则hashmap相关的实现 在RulesApplication类中,尝试获取spring上下文和执行线程bean,然后启动此线程
ApplicationContext conttext = SpringApplication.run(RulesApplication.class, args);
LocalRulesHandling handling = context.getBean(LocalRulesHandling.class);
handling.start();