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();
}
}
The Spring MVC form tags are the configurable and reusable building blocks for a web page. These tags provide JSP, an easy way to develop, read and maintain. The Spring MVC form tags can be seen as data binding-aware tags that can automatically set data to Java object/bean and also retrieve from it.
Spring MVC Form Tags are the reusable building blocks of a web page. These Spring tags are used for data binding that automatically sets data to Java object/bean and retrieves from it. It makes an application easy to develop, read, and maintain.
To use Spring's form tags in our web application, we need to include the below directive at the top of the JSP page. This form tag library comes bundled in spring-webmvc. jar and the library descriptor is called spring-form. tld.
JavaServer Pages Tag Library (JSTL) is a set of tags that can be used for implementing some common operations such as looping, conditional formatting, and others.
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();
}
}
You should prefer to put that logic into your controller. If you really need to do that you can write a utility class to retrieve beans from the application context.
public class AppContextUtil implements ApplicationContextAware
{
private static final AppContextUtil instance = new AppContextUtil();
private ApplicationContext applicationContext;
private AppContextUtil() {}
public static AppContextUtil getInstance()
{
return instance;
}
public <T> T getBean(Class<T> clazz)
{
return applicationContext.getBean(clazz);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
this.applicationContext = applicationContext;
}
}
You would then be able to retrieve your bean like this:
AppContextUtil.getInstance().getBean(MyObject.class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With