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

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

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/

        StudentRestController.java
import com.luv2code.demo.code.CompleteAsyncTask;
import com.luv2code.demo.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.CompletableFuture;
@EnableAsync
@RestController
@RequestMapping("/api")
public class StudentRestController {
//define endpoint for "/student" - return a list of students
@Autowired
private CompleteAsyncTask completeAsyncTask;
@GetMapping("/students")
public String getStudents() throws Exception {
long start = System.currentTimeMillis();
CompletableFuture<String> one = completeAsyncTask.doTaskOne();
CompletableFuture<String> two = completeAsyncTask.doTaskTwo();
CompletableFuture<String> three = completeAsyncTask.doTaskThree();
CompletableFuture.allOf(one, two, three).join();
System.out.println("Total time spent: " + (System.currentTimeMillis() - start));
System.out.println(one.get());
System.out.println(two.get());
System.out.println(three.get());
return "";
}
}
-----------------------------------------------------------------------------------
package com.luv2code.demo.code;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class CompleteAsyncTask {
public static Random random = new Random();
@Async
public CompletableFuture<String> doTaskOne() throws Exception {
System.out.println("Start doing asynchronous tasks one");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("complete asynchronous task one,time consuming:" + (end - start) + "millisecond");
return CompletableFuture.completedFuture("Task one completed");
}
@Async
public CompletableFuture<String> doTaskTwo() throws Exception {
System.out.println("Start doing asynchronous tasks two");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("complete asynchronous task two,time consuming:" + (end - start) + "millisecond");
return CompletableFuture.completedFuture("Task two completed");
}
@Async
public CompletableFuture<String> doTaskThree() throws Exception {
System.out.println("Start doing asynchronous tasks three");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("complete asynchronous task three,time consuming:" + (end - start) + "millisecond");
return CompletableFuture.completedFuture("Task three completed");
}
}
--------------------------------------------------------------------------------------
run result
2023-07-27T14:33:16.459+08:00  INFO 20612 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
Start doing asynchronous tasks one
Start doing asynchronous tasks two
Start doing asynchronous tasks three
complete asynchronous task three,time consuming:1055millisecond
complete asynchronous task two,time consuming:3981millisecond
complete asynchronous task one,time consuming:6468millisecond
Total time spent: 6475
Task one completed
Task two completed
Task three completed
------------------------------------------------------------------------------------
error message
Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2023-07-27 14:25:29.832 [restartedMain] ERROR org.springframework.boot.SpringApplication - Application run failed
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
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1314)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1199)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:560)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:520)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:973)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:917)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:584)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:732)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:310)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1304)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1293)
at com.xxx.mainApplication.main(mainApplication.java:20)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.xxx.testController]: Constructor threw exception
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:224)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1308)
... 22 common frames omitted
Caused by: java.lang.Error: Unresolved compilation problems: 
The import com.xxx.CompleteAsyncTask cannot be resolved
CompleteAsyncTask cannot be resolved to a type
at com.xxx.testController.<init>(testController.java:61)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:198)
... 24 common frames omitted

Other_project
test_controller --->call CompleteAsyncTask.java

I put this code in test_controller and show error.

@Autowired
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:

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

答案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.

Origin
@SpringBootApplication
@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;})
public class MainApplication {
// Main method and other configurations
}
new
@SpringBootApplication
@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;})
public class MainApplication {
// Main method and other configurations
}

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:

确定