我无法在Spring的后台运行该方法

时间:2018-07-15 14:04:53

标签: java spring multithreading

我有一个服务DocumentServiceImpl。

我要在其中运行index()的方法class GlobalSearch在后​​台运行。

@Service
@RequiredArgsConstructor
 public class DocumentServiceImpl implements DocumentService { 

... any code

@Transactional
 public void save(){

...

  Thread indexTread = new Thread(new GlobalSearch(file, id), "GlobalSearch");
  indexTread.start();

....

 }

}

GlobalSearch类的方法index使用类ExtractTextFromFile中的方法。我使用构造函数和Lombok注释@RequiredArgsConstructor注入类ExtractTextFromFile

@Component
@RequiredArgsConstructor
 public class GlobalSearch implements Runnable{
 public final ExtractTextFromFile extractTextFromFile; (41 lines)

 public File file;
 public Long id;
 public GlobalSearch(File File, Long id){
    this.file = file;
    this.id = id;
}

public void index(File file, Long id) {
    File textFile = extractTextFromFile.toText(file, id);

 ... code of this method

}

@Override
public void run() {
    index(file, id);
}

...other methods
public void search(){...}
public String delete(){...}

}

..但IDE为Variable 'extractTextFromFile' might not have been initialize给出了public final ExtractTextFromFile extractTextFromFile;

如果我使用以下方式注入:

@Autowired
ExtractTextFromFile extractTextFromFile;

然后显示错误:

Exception in thread "GlobalSearch" java.lang.NullPointerException
at bps.module.zxc.component.GlobalSearch.index(GlobalSearch.java:41)
at bps.module.zxc.component.GlobalSearch.run(GlobalSearch.java:136)
at java.lang.Thread.run(Thread.java:748)

此类ExtractTextFromFile:

@Component
@RequiredArgsConstructor
 public class ExtractTextFromFile {
 public File toText(File file, Long id) {
  extractFromPfd();
  extractFromWord();
 }
  extractFromPfd(){...};
  extractFromWord(){...};
 }

2 个答案:

答案 0 :(得分:0)

我解决了这个问题,我删除了GlobalSearch和ExtractTextFromFile类的注解@Component,然后使用

将它们初始化为简单的句柄
 GlobalSearch globalSearch = new GlobalSearch() 

...和

 ExtractTextFromFile extractTextFromFile = new ExtractTextFromFile()

答案 1 :(得分:0)

您为什么不尝试使用@asyc方法和@EnableAsyc

@Async
     public void looper()
     {
        try {
            Thread.sleep(15000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        for(int i=0;i<20000;i++)
        {
            System.out.println("hitting "+i);
        }
     }

在配置上使用@EnableAsync

@SpringBootApplication
@EnableAsync
public class SpringbootdemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootdemoApplication.class, args);
    }
}