gpt4 book ai didi

java - 如何声明一个具有以 String 和 Map 作为参数的构造函数的 bean?

转载 作者:行者123 更新时间:2023-11-30 04:36:58 26 4
gpt4 key购买 nike

我正在使用 ThreadPoolExecutor 实用程序并通过被调用类中的构造函数传递值。构造函数采用两个参数 (1) 一个映射 (2) 一个字符串。

我对如何为被调用的类声明一个 bean 感到困惑,该类需要两个参数(一个映射和一个字符串)。我的代码如下。

***Calling Class***

public class Starter {

ProcessScheduler deleteBatch;
public ProcessScheduler getDeleteBatch() {
return deleteBatch;
}

public void setDeleteBatch(ProcessScheduler deleteBatch) {
this.deleteBatch = deleteBatch;
}


public void start() {

ThreadPoolExecutor executor = testThreadPoolExecutorService.createNewThreadPool();


for (int i=0;i<=5;i++)
{
Map m4 = arrayRecords.get(i);
executor.execute(new ProcessScheduler("Thread #"+i,m4)); // Comment - started
The above line executes fine but it gives null pointer error if I will call any other method from the run() inside called class(ProcessScheduler). So I have use a Bean such as executor.execute(getDeleteBatch("Thread #"+i,m4)) to get the instance of the bean. But I dont know how to do this in this case?

// Comment - ended


}

***Called Class***



public class ProcessScheduler implements Runnable {

public ProcessScheduler(String taskName, Map m) {
this.taskName = taskName;
this.deleteRecordsMap = (HashMap) m;
}
Processor processor;
public Processor getProcessor()
{
return processor;
}


public void setProcessor(Processor mappProcessor) {
this.mappProcessor = mappProcessor;
}


public void run()
{
// This returns null
processor.getNumbers();
}

}



I have some confusions as below.
(1) How to declare a bean for ProcessScheduler in this case.
(2) Is the declaration of getDeleteBatch is correct in this case like below?

public ProcessScheduler getDeleteBatch() {
return deleteBatch;
}

谢谢正达夫

最佳答案

你真的认为这是个好主意吗?

public ProcessScheduler(String taskName, Map m) {
this.taskName = taskName;
this.RecordsMap = (HashMap) m;
}

我认为应该更像这样:

public ProcessScheduler(String taskName, Map m) {
this.taskName = taskName;
this.recordsMap = new HashMap(m); // You don't want changes to the Map passed in to show up in your private data member.
}

我不确定您是否可以将 ProcessScheduler 实例从 Spring 作为 Bean 注入(inject);在这种情况下,您可能确实想为每个执行程序服务创建一个新的服务。

Spring 不需要控制应用程序中的每个 bean。

关于java - 如何声明一个具有以 String 和 Map 作为参数的构造函数的 bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13259248/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com