zoukankan      html  css  js  c++  java
  • 方法调用---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();  

    即可。

  • 相关阅读:
    Codeforces 1154C Gourmet Cat
    copy 浅拷贝 深拷贝
    sort and sorted 区别
    python第四天
    python入门第三天_练习
    可持久化trie
    bzoj 3261 最大异或和【可持久化trie】
    bzoj 2716 [Violet 3]天使玩偶 【CDQ分治】
    bzoj 1176 [Balkan2007]Mokia 【CDQ分治】
    CDQ分治
  • 原文地址:https://www.cnblogs.com/ShaYeBlog/p/7060456.html
Copyright © 2011-2022 走看看