簡體   English   中英

在springboot中使用@Autowired時出錯

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM