您的位置 首页 java

java方法调用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();  

即可。

文章来源:智云一二三科技

文章标题:java方法调用controller的方法

文章地址:https://www.zhihuclub.com/187886.shtml

关于作者: 智云科技

热门文章

网站地图