如何调用controller类里的方法

我们有一个路由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();
即可。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值