gpt4 book ai didi

java - 如何从外部 Controller 运行 Controller 内的方法

转载 作者:行者123 更新时间:2023-12-01 14:03:42 24 4
gpt4 key购买 nike

我有一个 Controller 类:

@Controller
public class MyController {

@AutoWired
Service myservice

@RenderMapping
public display(){
//do work with myservice
}

}

我想从外部类调用方法display(),但我是一个空指针异常。

以下是我从外部类调用显示方法的方法:

new MyController.display()

但是实例 myservice 被设置为 null。

如何调用 MyController.display() 并确保 myservice 的实例不设置为 null ?

我认为问题是因为我正在创建 Controller 的新实例,所以服务不会自动连接?但由于 Spring Controller 是单例,也许我可以访问 Controller 的当前实例?

更新:

我尝试这样做的原因是我添加了一个配置选项来确定应实现哪种 Controller 显示方法。也许我应该使用 super Controller 来确定应该实现哪个 Controller ?

最佳答案

想法是:使用抽象父类!

// this class has no mapping
public abstract class MyAbstractController() {
@Autowired
MyService service

public String _display(Model model, ...) {
// here is the implementation of display with all necessary parameters
if(determine(..)){...}
else {...}
}

// this determines the behavior of sub class
public abstract boolean determin(...);
}

@Controller
@RequestMapping(...)
public class MyController1 extends MyAbstractController {

@RequestMapping("context/mapping1")
public String display(Model model, ...) {
// you just pass all necessary parameters to super class, it will process them and give you the view back.
return super._display(model, ...);
}

@Override
public boolean determine(...) {
// your logic for this
}
}

@Controller
@RequestMapping(...)
public class MyController2 extends MyAbstractController {

@RequestMapping("context/mapping2")
public String display(Model model, ...) {
// you just pass all necessary parameters to super class, it will process them and give you the view back.
return super._display(model, ...);
}

@Override
public boolean determine(...) {
// your logic for this
}
}

希望这可以帮助你...

关于java - 如何从外部 Controller 运行 Controller 内的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19114008/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com