Introductory dependency in a static field

I want to create a template engine in servlets. The specific implementation of the template engine must be changed behind the TemplateEngine interface. With a regular dependency injection, it might look like this:

public abstract class BaseServlet extends HttpServlet {

    private TemplateEngine templateEngine;

    public void setTemplateEngine(TemplateEngine te) {
      templateEngine = te;
    }

    protected void render(Result result, HttpServletResponse response) {
      templateEngine.render(result, resonse);
    }

}

The disadvantage of this approach is that every servlet that wants to use the rendering method must extend the BaseServlet. Therefore, I would like to have a statically imported renderer method.

public class TemplateEngineWrapper {

  @Inject
  static TemplateEngine templateEngine;

  public static void render(Result result, HttpServletResponse response) {
    templateEngine.render(result, resonse);
  }

}

In the servlet, I will use it like this:

import static TemplateEngineWrapper.render;

...

public void doGet(...) {
  render(new Result(200, "Everything is fine."), response);
}

...

Is there something wrong with this approach? If yes: what would you suggest instead?

+3
source share
1 answer

, ( ). . , , :

  @Inject
  private TemplateEngine templateEngine;

BaseServlet (, ).

+7

Source: https://habr.com/ru/post/1727251/


All Articles