【问题标题】:Getting error while using @Autowired in the springboot在springboot中使用@Autowired时出错
【发布时间】:2021-01-14 23:56:18
【问题描述】:

我正在创建一个 Springboot 项目,其中我有两个服务接口,我将它们注入到我的控制器中

学生服务

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 惹恼的两个接口的实现?
  • 你得到什么样的错误?
  • StudentService 和 StudenService 之间有错别字

标签: java spring spring-boot


【解决方案1】:

用@Service注解来注解服务类

@服务 公共接口 TeacherService {

void addStudent(Teacher teacher);
//other functions

}

【讨论】:

    【解决方案2】:

    尝试在 ServiceImpl 类上使用 @Service 并重试。我认为这应该可以解决您的问题。

    【讨论】:

      【解决方案3】:

      @Autowired 将用于在容器内的两个 objectS 之间创建链接。 看来您在 StudentService 实现中使用了 @service 或 @component,而在 TeacherService 实现中错过了它。

      请确保使用 @component 来实现 TeacherService。所以通过这种方式,对象将在容器内创建。

      @Service or @component
      public class TeacherServiceImp implements TeacherService {
      //your code
      }
      

      【讨论】:

        【解决方案4】:

        我们也可以在这里使用@Component 为TeacherServiceImpl 类创建bean。我认为两者都会起作用。

        @Service
        public class TeacherServiceImp implements TeacherService {
        //your codes 
        }
        
        @Component
        public class TeacherServiceImp implements TeacherService {
        //your codes 
        }
        

        【讨论】:

          【解决方案5】:

          这种类型的错误通常发生在您可能没有在服务实现中使用@Service 或服务接口尚未实现时。

          @Service
          public class TeacherServiceImp implements TeacherService {
          //your codes
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-10-14
            • 2022-08-19
            • 2019-01-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多