开发者

Inject dependency into static field

I want to make template engine available in servlets. The concrete template engine implementation should be changeable behind the TemplateEngine interface. With usual dependency injection it could 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 each Servlet that wants to use the render method has to extend BaseServlet. Therefore I'd like to have a statically imported render method.

public class TemplateEngineWrapper {

  @Inject
  static TemplateEngine templateEngine;

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

}
开发者_如何学编程

In the Servlet I would use it this way:

import static TemplateEngineWrapper.render;

...

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

...

Is something wrong with this approach? If so: What would you suggest instead?


The problem with this approach is that it tightly couples your Servlets to a single implementation of render (it's a singleton in disguise). Avoiding this tight coupling is a major benefit of Dependency Injection. It would be better to have the renderer injected into each servlet using:

  @Inject
  private TemplateEngine templateEngine;

if you want to avoid having to inherit from BaseServlet (understandable because it locks you into one class hierarchy).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜