javaspring-mvctaglib

Spring MVC and custom tags


I want to use spring-beans in my custom taglibs in a spring-mvc application. Cause TagLib-Instances aren't instantiated by spring, I can't use dependnecy-injection.

My next thought was to add the spring-context by an interceptor to the request and get it from request within the tag-class.

Is there a better way to use spring in taglibs? Is there something ready-to-use in spring? If theres not already customtag-support in spring-mvc, is there a way to populate an exisiting object with dependencies?

public class MyTag extends TagSupport {
  @Autowired 
  private MyObject object;

  public void setMyObject(MyObject myObject) {
    this.myObject = myObject;
  }

  public int doEndTag() {
    ApplicationContext context = request.getAttribute("context");
    context.populate(this);

    return object.doStuff();
  }
}

Solution

  • Finally, the working way to do this was to declare the fields that should be initiated by spring as static and let initiate one Tag-instance

    public class MyTag extends TagSupport {
      private static MyObject myObject;
    
      @Autowired
      public void setMyObject(MyObject myObject) {
        MyTag.myObject = myObject;
      }
    
      public int doEndTag() {
        return object.doStuff();
      }
    }