Spring Boot错误:构造函数抛出异常

huangapple go评论102阅读模式
英文:

Spring boot error : Constructor threw exception

问题

我是一个学习Spring Boot的新手。我想学习在Spring Boot中如何使用@Async函数。我创建了一个新的Spring Boot项目并放置了代码。一切都很好,我得到了结果。
但是当我将代码放入我的其他项目中时,我遇到了错误,不知道发生了什么。

你提供的代码中有两个类:StudentRestController和CompleteAsyncTask。StudentRestController是一个控制器类,用于定义API接口。CompleteAsyncTask是一个组件类,用于执行异步任务。

在StudentRestController中,使用@Autowired注解将CompleteAsyncTask注入进来,并在getStudents方法中调用CompleteAsyncTask的三个异步任务方法:doTaskOne、doTaskTwo和doTaskThree。然后使用CompletableFuture.allOf方法等待所有异步任务完成,并打印结果。

CompleteAsyncTask类中定义了三个异步任务方法:doTaskOne、doTaskTwo和doTaskThree。这些方法使用@Async注解表示它们是异步执行的。每个方法都会打印开始执行的消息,然后通过Thread.sleep模拟一段耗时的操作,最后返回一个CompletableFuture对象。

你提供的运行结果显示了异步任务的执行情况和总耗时。然后,你提供了一个错误消息,显示了在另一个项目中使用CompleteAsyncTask时遇到的问题。

根据错误消息,问题可能是由于找不到CompleteAsyncTask类导致的。请确保CompleteAsyncTask类在你的项目中正确引入,并且包名和类名都正确。

希望这些信息对你有帮助!如果你有任何其他问题,请随时问我。

英文:

I'm a new guy to learn spring boot. I want to learn @Async function how to work in spring boot. I create new spring boot and put the code. Everything is great, I got the result.
When I put the code in to my other project. I got error and I don't know what happen.

web: https://morosedog.gitlab.io/springboot-20190421-springboot33/

  1. StudentRestController.java
  2. import com.luv2code.demo.code.CompleteAsyncTask;
  3. import com.luv2code.demo.entity.Student;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.scheduling.annotation.EnableAsync;
  6. import org.springframework.web.bind.annotation.GetMapping;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RestController;
  9. import java.util.concurrent.CompletableFuture;
  10. @EnableAsync
  11. @RestController
  12. @RequestMapping("/api")
  13. public class StudentRestController {
  14. //define endpoint for "/student" - return a list of students
  15. @Autowired
  16. private CompleteAsyncTask completeAsyncTask;
  17. @GetMapping("/students")
  18. public String getStudents() throws Exception {
  19. long start = System.currentTimeMillis();
  20. CompletableFuture<String> one = completeAsyncTask.doTaskOne();
  21. CompletableFuture<String> two = completeAsyncTask.doTaskTwo();
  22. CompletableFuture<String> three = completeAsyncTask.doTaskThree();
  23. CompletableFuture.allOf(one, two, three).join();
  24. System.out.println("Total time spent: " + (System.currentTimeMillis() - start));
  25. System.out.println(one.get());
  26. System.out.println(two.get());
  27. System.out.println(three.get());
  28. return "";
  29. }
  30. }
  31. -----------------------------------------------------------------------------------
  32. package com.luv2code.demo.code;
  33. import java.util.Random;
  34. import java.util.concurrent.CompletableFuture;
  35. import org.springframework.scheduling.annotation.Async;
  36. import org.springframework.stereotype.Component;
  37. @Component
  38. public class CompleteAsyncTask {
  39. public static Random random = new Random();
  40. @Async
  41. public CompletableFuture<String> doTaskOne() throws Exception {
  42. System.out.println("Start doing asynchronous tasks one");
  43. long start = System.currentTimeMillis();
  44. Thread.sleep(random.nextInt(10000));
  45. long end = System.currentTimeMillis();
  46. System.out.println("complete asynchronous task onetime consuming:" + (end - start) + "millisecond");
  47. return CompletableFuture.completedFuture("Task one completed");
  48. }
  49. @Async
  50. public CompletableFuture<String> doTaskTwo() throws Exception {
  51. System.out.println("Start doing asynchronous tasks two");
  52. long start = System.currentTimeMillis();
  53. Thread.sleep(random.nextInt(10000));
  54. long end = System.currentTimeMillis();
  55. System.out.println("complete asynchronous task twotime consuming:" + (end - start) + "millisecond");
  56. return CompletableFuture.completedFuture("Task two completed");
  57. }
  58. @Async
  59. public CompletableFuture<String> doTaskThree() throws Exception {
  60. System.out.println("Start doing asynchronous tasks three");
  61. long start = System.currentTimeMillis();
  62. Thread.sleep(random.nextInt(10000));
  63. long end = System.currentTimeMillis();
  64. System.out.println("complete asynchronous task threetime consuming:" + (end - start) + "millisecond");
  65. return CompletableFuture.completedFuture("Task three completed");
  66. }
  67. }
  68. --------------------------------------------------------------------------------------
  69. run result
  70. 2023-07-27T14:33:16.459+08:00 INFO 20612 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
  71. Start doing asynchronous tasks one
  72. Start doing asynchronous tasks two
  73. Start doing asynchronous tasks three
  74. complete asynchronous task threetime consuming1055millisecond
  75. complete asynchronous task twotime consuming3981millisecond
  76. complete asynchronous task onetime consuming6468millisecond
  77. Total time spent: 6475
  78. Task one completed
  79. Task two completed
  80. Task three completed
  81. ------------------------------------------------------------------------------------
  82. error message
  83. Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
  84. 2023-07-27 14:25:29.832 [restartedMain] ERROR org.springframework.boot.SpringApplication - Application run failed
  85. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testController' defined in file [D:\xxxxx\testController.class]: Failed to instantiate [com.xxx.testController]: Constructor threw exception
  86. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1314)
  87. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1199)
  88. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:560)
  89. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:520)
  90. at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326)
  91. at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
  92. at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324)
  93. at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
  94. at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:973)
  95. at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:917)
  96. at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:584)
  97. at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146)
  98. at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:732)
  99. at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434)
  100. at org.springframework.boot.SpringApplication.run(SpringApplication.java:310)
  101. at org.springframework.boot.SpringApplication.run(SpringApplication.java:1304)
  102. at org.springframework.boot.SpringApplication.run(SpringApplication.java:1293)
  103. at com.xxx.mainApplication.main(mainApplication.java:20)
  104. at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  105. at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
  106. at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  107. at java.base/java.lang.reflect.Method.invoke(Method.java:568)
  108. at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
  109. Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.xxx.testController]: Constructor threw exception
  110. at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:224)
  111. at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87)
  112. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1308)
  113. ... 22 common frames omitted
  114. Caused by: java.lang.Error: Unresolved compilation problems:
  115. The import com.xxx.CompleteAsyncTask cannot be resolved
  116. CompleteAsyncTask cannot be resolved to a type
  117. at com.xxx.testController.<init>(testController.java:61)
  118. at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
  119. at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
  120. at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
  121. at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
  122. at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
  123. at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:198)
  124. ... 24 common frames omitted

Other_project
test_controller --->call CompleteAsyncTask.java

I put this code in test_controller and show error.

  1. @Autowired
  2. private CompleteAsyncTask completeAsyncTask;

答案1

得分: 1

请检查一下你的导入语句。错误提示表明控制器未被识别。

错误原因:java.lang.Error: 未解析的编译问题:
导入 com.xxx.CompleteAsyncTask 无法解析
CompleteAsyncTask 无法解析为类型

请验证包结构:确保 CompleteAsyncTask 类位于正确的包中。例如,如果 CompleteAsyncTask 类位于 com.luv2code.demo.code 包中,请确保它在项目的正确文件夹结构中。

同时,请确保在主应用程序类中使用 @ComponentScan 注解将其包含在组件扫描中。例如:

@SpringBootApplication
@ComponentScan(basePackages = {"com.luv2code.demo.code", "com.luv2code.demo.entity", "com.luv2code.demo.rest"})
public class MainApplication {
// 主方法和其他配置
}

英文:

can you please check your import once. Error indicates controller was not recognized.

Caused by: java.lang.Error:<b> Unresolved compilation problems:
The import com.xxx.CompleteAsyncTask</b> cannot be resolved
CompleteAsyncTask cannot be resolved to a type

Verify Package Structure: Ensure that the CompleteAsyncTask class is in the correct package. For example, if the CompleteAsyncTask class is in the package com.luv2code.demo.code, make sure it is in the correct folder structure within your project.

make sure to include it in the component scanning by using @ComponentScan annotation in your main application class. For example:

  1. @SpringBootApplication
  2. @ComponentScan(basePackages = {&quot;com.luv2code.demo.code&quot;, &quot;com.luv2code.demo.entity&quot;, &quot;com.luv2code.demo.rest&quot;})
  3. public class MainApplication {
  4. // Main method and other configurations
  5. }

答案2

得分: 0

我将展示如何解决这个问题。
"com.luv2code.demo.contoller"是ComponentScan中的第一个。
所以,我将"com.luv2code.demo.code"的位置改为第一个。

原始代码:

@SpringBootApplication
@ComponentScan(basePackages ={"com.luv2code.demo.contoller","com.luv2code.demo.code", "com.luv2code.demo.entity", "com.luv2code.demo.rest"})
public class MainApplication {
// 主方法和其他配置
}

修改后的代码:

@SpringBootApplication
@ComponentScan(basePackages = {"com.luv2code.demo.code","com.luv2code.demo.contoller", "com.luv2code.demo.entity", "com.luv2code.demo.rest"})
public class MainApplication {
// 主方法和其他配置
}

现在,我可以运行我的项目了。

英文:

I will show how to slove the question.
"com.luv2code.demo.contoller" is first one in the ComponentScan.
So, I change "com.luv2code.demo.code" position to first.

  1. Origin
  2. @SpringBootApplication
  3. @ComponentScan(basePackages ={&quot;com.luv2code.demo.contoller&quot;,&quot;com.luv2code.demo.code&quot;, &quot;com.luv2code.demo.entity&quot;, &quot;com.luv2code.demo.rest&quot;})
  4. public class MainApplication {
  5. // Main method and other configurations
  6. }
  7. new
  8. @SpringBootApplication
  9. @ComponentScan(basePackages = {&quot;com.luv2code.demo.code&quot;,&quot;com.luv2code.demo.contoller&quot;, &quot;com.luv2code.demo.entity&quot;, &quot;com.luv2code.demo.rest&quot;})
  10. public class MainApplication {
  11. // Main method and other configurations
  12. }

Right now, I can run my project.

huangapple
  • 本文由 发表于 2023年7月27日 15:03:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76777231.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定