解决NoSuchBeanDefinitionException: No qualifying bean of type ‘bean.User‘ available

After springboot started, the following error occurred. The compiler told us that there was no matching bean.

Insert image description here

The following is the code in the startup class:

package com.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;



@SpringBootApplication
public class MainApplication {
    
    
    public static void main(String[] args) {
    
    
      ConfigurableApplicationContext run= SpringApplication.run(MainApplication.class,args);
      User user=new User("张三",21);
      run.getBean(User.class);
      System.out.println(user);
    }
}

User class:

package com.springboot;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Controller;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Controller
public class User {
    
    
    private String name;
    private Integer age;
}

The reason for the above error is that when springboot's startup class scans components, it will only scan the package and sub-packages where the startup class is located . Later, I checked and it was indeed the case, as shown below:

Insert image description here

User is indeed not under the startup class package or sub-package, so it is not scanned.

The solution is as follows:

We only need to add the component User to the package or sub-package of the startup class!

Insert image description here

The output looks like this:

Insert image description here

Guess you like

Origin blog.csdn.net/m0_64365419/article/details/133550562