我们有一个路由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();
即可。
我们有一个路由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();
即可。
本文介绍了在Spring MVC框架中,如何在GradeController中调用StudentController的count()方法。两种方法包括:直接通过new关键字创建实例调用,但可能遇到空指针异常;另一种是利用@Autowired注解进行依赖注入,确保所有服务自动注入并可用。推荐使用@Autowired注解以简化代码并确保依赖的正确管理。
870

被折叠的 条评论
为什么被折叠?



