[英]Getting error while using @Autowired in the springboot
我正在创建一个 Springboot 项目,其中有两个服务接口,我将它们注入我的 Controller
学生服务
public interface StudentService {
void addStudent(Student student);
//other functions
}
教师服务
public interface TeacherService {
void addStudent(Teacher teacher);
//other functions
}
当我将 @Autowired 用于 StudentService 时,它工作正常,但是当我在 Controller 中将 @Autowired 用于 TeacherService 时出现错误。我尝试了很多但没有找到错误的原因。
我的控制器
@Controller
public class StudentController {
@Autowired
StudenService studenService;
....
....
}
@Controller
public class TeacherController {
@Autowired
TeacherService teacherService;
....
....
}
使用 @Service 注释注释服务 class
@Service 公共接口 TeacherService {
void addStudent(Teacher teacher);
//other functions
}
尝试在 ServiceImpl class 上使用 @Service 并重试。 我认为这应该可以解决您的问题。
@Autowired 将用于在容器内的两个 objectS 之间创建链接。 您似乎在 StudentService 实现中使用了 @service 或 @component 而在 TeacherService 实现中错过了它。
请确保使用 @component 来实现 TeacherService。 所以通过这种方式,object 将在容器内创建。
@Service or @component
public class TeacherServiceImp implements TeacherService {
//your code
}
我们也可以在这里使用@Component 为TeacherServiceImpl
class 创建 bean。 我认为两者都会起作用。
@Service
public class TeacherServiceImp implements TeacherService {
//your codes
}
@Component
public class TeacherServiceImp implements TeacherService {
//your codes
}
此类错误通常发生在您可能尚未在 Service 实现中使用 @Service 或尚未实现服务接口时。
@Service
public class TeacherServiceImp implements TeacherService {
//your codes
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.