如何从控制器调用服务

时间:2018-07-27 22:20:53

标签: spring spring-boot sendgrid

我正在尝试从控制器调用以下服务:

@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对象。

2 个答案:

答案 0 :(得分:1)

正如其他人所建议的那样,我确实认为您也需要花费更多的时间来学习Java和Spring基础知识。但是要回答您的问题,您可以在控制器中自动连线/注入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";
}
  .
  .
  .

}

答案 1 :(得分:1)

您可以通过以下方式致电服务

1)只需将@Autowired添加到您的班级类型

@Autowired
MyMailService myMailService;

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

MyMailService myMailService;    

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


-  here i assumed my Controller name is WebController

3)按如下方式使用Setter注入,

MyMailService myMailService;

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

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

myMailService.sendMail();

注意: 遵循命名约定。