SpringBoot报Consider defining a bean of type ‘xxx’ in your configuration怎么解决
首先看下代码:问题是自动注入User类的user对象失败,意思就是没有找到这个类,即这个类没有注入到Spring容器中。
(service实现类已经加了@service注解)
@RestController
public class UserController {
@Autowired
User user;
@Autowired
private UserServiceImpl userServiceImpl;
@GetMapping("/user")
public List<User> queryUser(){
List<User> users = userServiceImpl.getUser();
return users;
}
@GetMapping("/adduser")
public void addUser(){
user.setName("qiang");
user.setAge(666);
userServiceImpl.addUser(user);
}
}
解决方法
给user类添加@Configuration注解
(或者添加@Component注解也可以解决)
@Configuration
public class User {
private int id;
private String name;
private int age;
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public User() {
}
这时候再重启代码就可以了
两个注解的解释
@Component注解
@component:把普通pojo实例化到spring容器中,
相当于配置文件中的 <bean id="" class=""/>
,泛指各种组件,就是说当我们的类不属于各种归类的时候(不属于@Controller、@Services等的时候),我们就可以使用@Component来标注这个类。
@Configuration注解
@Configuration一般注解在这样的类上:这个类里面有@Value注解的成员变量和@Bean注解的方法
@Component注解的范围最广,所有类都可以注解
@configuration和@component相同点是都是注解在类上的注解
更多推荐
SpringBoot报错Consider defining a bean of type ‘xxx’ in your configuration
发布评论