方法調用---springMVC中調用controller的方法


我們有一個路由StudentController,里面有一個方法count()。如果要在另外一個GradeController中調用count()方法有2種方式:

因為StudentController是一個class,不是接口,接口一般都是@Autowired注入就能調用。

new一個實例調用

比如在GradeController的方法中new一個StudentController然后調用。

 

[plain]  view plain  copy
 
  1. StudentController   studentController=new StudentController ();  
  2. int count=studentController.count();  

 

即可。

 

這種情況是在 count方法中 沒有使用 其它@Autowired引入的接口service的情況下。否則會報錯空指針。因為new 出來的實例是不帶StudentController中注入的。

如果count方法中使用了 其它@Autowired引入的接口service,則需要修改一下,把這個service作為參數傳入count方法中。

GradeController中也需要@Autowired引入的接口service,然后

 

[plain]  view plain  copy
 
  1. @Autowired  
  2. Service  service;  
  3. StudentController   studentController=new StudentController ();  
  4. int count=studentController.count(service);  

 

 

如果調用的service太多,則需要傳入 改動的地方就比較多。

 

 

@Autowired注解調用(推薦)

我們不new一個實例,直接把StudentController 自動注解進 GradeController即可直接使用,這種情況下,StudentController @Autowired引入的接口service也會自動注入。

也就是在GradeController中:

 

 

[plain]  view plain  copy
 
  1. @Autowired  
  2. StudentController  studentController ;  
  3. int count=studentController.count();  

 

即可。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM