我們有一個路由StudentController,里面有一個方法count()。如果要在另外一個GradeController中調用count()方法有2種方式:
因為StudentController是一個class,不是接口,接口一般都是@Autowired注入就能調用。
new一個實例調用
比如在GradeController的方法中new一個StudentController然后調用。
- StudentController studentController=new StudentController ();
- int count=studentController.count();
即可。
這種情況是在 count方法中 沒有使用 其它@Autowired引入的接口service的情況下。否則會報錯空指針。因為new 出來的實例是不帶StudentController中注入的。
如果count方法中使用了 其它@Autowired引入的接口service,則需要修改一下,把這個service作為參數傳入count方法中。
GradeController中也需要@Autowired引入的接口service,然后
- @Autowired
- Service service;
- StudentController studentController=new StudentController ();
- int count=studentController.count(service);
如果調用的service太多,則需要傳入 改動的地方就比較多。
@Autowired注解調用(推薦)
我們不new一個實例,直接把StudentController 自動注解進 GradeController即可直接使用,這種情況下,StudentController @Autowired引入的接口service也會自動注入。
也就是在GradeController中:
- @Autowired
- StudentController studentController ;
- int count=studentController.count();
即可。