在springboot启动后,发生如下错误,编译器告诉我们是没有匹配的Bean
如下所示为启动类中的代码:
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类:
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; }
去检查了一下确实如此,如下所示:
User确实不在启动类的包或者子包下,所以导致出现了没有被扫描到的情况
解决办法如下所示:
我们只需要将组件User添加至启动类的包或者子包下即可!
输出如下所示: