[Solved] “Field pet in XXX.HelloController required a bean of type ‘XXX.Pet‘ that could not be found.“

abnormal

2021-06-22 14:10:56.860 ERROR 17884 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field pet in com.demo.springboot.controller.HelloController required a bean of type 'com.demo.springboot.bean.Pet' that could not be found.

The injection point has the following annotations:
	- @org.springframework.beans.factory.annotation.Autowired(required=true)

The following candidates were found but could not be injected:
	- Bean method 'pet' in 'MyConfig' not loaded because @ConditionalOnBean (names: user01; SearchStrategy: all) did not find any beans named user01


Action:

Consider revisiting the entries above or defining a bean of type 'com.demo.springboot.bean.Pet' in your configuration.

reason

Let’s analyze the printed error log

Let’s look at the hellocontroller class, in which the bean component of pet type is injected, but an error is reported that the injection is not successful

Then, we click the arrow icon on the left to go to the method of injecting this component. We find that it is the pet () method of the myconfig class, where the @ bean annotation is used to inject the pet component.

However, we use @ conditionalonbean (name = user01) annotation above the @ bean annotation, which means that a component named “user01” must exist in the container before the pet component can be injected, otherwise it will not be injected.

solve

Cancel the @ conditionalonbean (name = user01) annotation, or inject a component named “user01”.

But what is the reason for this mistake?Note that the bean component to be used by the @ conditionalonbean annotation condition should be declared above the annotation, not below.

Read More: