java无法调用“com.example.gestion.service.TestService.saveTest(testreport)”,因为“this.testRepository”为空
嗨,我正在尝试将多个线程与我的spring boot应用程序集成。我在我的服务中创建了一个类MyRunnable 这是我的班级:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Time;
import javax.annotation.PostConstruct;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.gestion.entity.Archive;
import com.example.gestion.entity.Lien;
import com.example.gestion.entity.TestRapport;
import com.example.gestion.repository.ApplicationsRepository;
import com.example.gestion.repository.ArchiveRepository;
public class MyRunnable implements Runnable {
private final Lien lien;
public static String message="";
@Autowired
TestService testRepository;
MyRunnable(Lien url) {
this.lien = url;
}
public static int hhttpcode(String site) throws IOException {
try {
URL url = new URL(site);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
return code;
}catch (Exception e)
{return 0;}}
public static void setMessage(String message) {
MyRunnable.message = message;
}
@Override
@PostConstruct
public void run() {
// TODO Auto-generated method stub
String msg="";
String type=lien.getTestType();
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
Time sqlTime = new Time(millis);
/////boucle if that gives me the String msg
/// enregistrer le test
TestRapport rapp=new TestRapport(lien,msg,date,sqlTime);
testRepository.saveTest(rapp);
}
}
当我运行它时,boucle if工作正常,但当涉及到保存实体时,它会给我以下错误:
Exception in thread "pool-1-thread-3" java.lang.NullPointerException: Cannot invoke "com.example.gestion.service.TestService.saveTest(com.example.gestion.entity.TestRapport)" because "this.testRepository" is null at com.example.gestion.service.MyRunnable.run(MyRunnable.java:298) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) at java.base/java.lang.Thread.run(Thread.java:832)
我试图将@PostConstruct添加到run()函数中,但没有成功 有人能帮我解决这个问题吗
# 1 楼答案
@PostConstruct和@Autowired只能在托管bean中使用
要使MyRunnable成为托管bean,可以使用@Component对其进行注释