当运行springBoot应用程序时,需要找不到类型的bean


@SpringBootApplication
@ComponentScan
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(MileageFeeController.class, args);    
}
}
@Controller
public class MileageFeeController { 
@Autowired 
MileageFeeCalculator calc;
public float mileageFee( int miles) {
System.out.println("Helloe");
return calc.mileageCharge(miles);
}
}
@Component
public class MileageFeeCalculator {
@Autowired
private MileageRateService rateService; 
public float mileageCharge(int miles) {
return (miles * rateService.ratePerMile());
}
}
@Component
public class MileageRateService {
public float ratePerMile() {
return 0.565f;
}
}

当执行上面的代码得到下面的错误

com.demo.DemoApplication : Starting DemoApplication using Java 17 on N13115 with PID 9336 (D:Spring ToolSpringWorkSpaceDemotargetclasses started by jitendra2.k in D:Spring ToolSpringWorkSpaceDemo)
com.demo.DemoApplication : No active profile set, falling back to default profiles: default
s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mileageFeeController': Unsatisfied dependency expressed through field 'calc'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.demo.MileageFeeCalculator' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2022-01-15 20:28:39.643 ERROR 9336 --- [main] o.s.b.d.LoggingFailureAnalysisReporter: 
***************************
APPLICATION FAILED TO START
***************************
Description:
Field calc in com.demo.MileageFeeController required a bean of type 'com.demo.MileageFeeCalculator' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.demo.MileageFeeCalculator' in your configuration.

您可以在DemoApplication类中尝试以下更改。不是将MileageFeeController.class传递给SpringApplication.run,而是传递DemoApplication.class

@SpringBootApplication
@ComponentScan
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

正如您提到的,您必须使用MileageFeeController.mileageFee方法,您应该以CommandLineRunner的身份运行SpringBoot应用程序,如下所示。

CommandLineRunner有一个运行方法,可以用来触发MileageFeeController.mileageFee方法

@SpringBootApplication
@ComponentScan
public class DemoApplication implements CommandLineRunner {
@Autowired
MileageFeeController feeController;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) {
System.out.println(feeController.mileageFee(5));
}
}

相关内容