如何从控制器调用服务?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (23)

我试图从控制器调用以下服务:

@Service
class MyMailService {

    private final SendGrid sendGrid;

    @Inject
    public SendGridMailService(SendGrid sendGrid) {
        this.sendGrid = sendGrid;
    }

    void sendMail() {
        Request request = new Request();
        Response response = this.sendGrid.api(request);                
    }
}

我的控制器:

# controller
public String index(Model model) {
    MyMailService.sendMail() // how to do this properly?
    return "register";
}

从控制器调用它的正确方法是什么?基本上,我正在尝试“自动配置”sendgrid,所以每当我调用MyMailService类时,我都不必使用API​​密钥初始化SendGrid对象。

提问于
用户回答回答于

1)只需将@Autowired添加到你的class类型

@Autowired
MyMailService myMailService;

2)使用如下构造函数注入

MyMailService myMailService;    

@Autowired
public WebController(MyMailService myMailService) {
    this.myMailService = myMailService;
}


-  here i assumed my Controller name is WebController

3)使用Setter Injection如下

MyMailService myMailService;

@Autowired
public void setMyMailService(MyMailService myMailService) {
    this.myMailService = myMailService;
}

最后在你的控制器中你可以调用你的服务类方法,如下所示,

myMailService.sendMail();
用户回答回答于

可以在service控制器中自动连接/注入单个对象以使用它:

@Controller
public class ControllerA
{
  .
  .
  .
  @Autowired
  private MyMailService mymailService; //singleton object instance injected to be used/shared by all controllers

public String index(Model model) {
    mymailService.sendMail()
    return "register";
}
  .
  .
  .

}

扫码关注云+社区

领取腾讯云代金券