Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject spring beans into a jsp 2.0 SimpleTag?

Currently my jsp 2.0 tags that need spring beans use this code:

ac = WebApplicationContextUtils.getWebApplicationContext( servletContext);
ac.getBeansOfType(MyRequestedClass.class);

The I just get the first matching bean.

This code works fine, but has the undesired drawback that I spend about half my page rendering time looking up spring beans, since this happens every time a tag is invoked. I was thinking maybe to put the bean into application scope or at least session scope. But what's really the smartest way of handling this problem ?

like image 618
krosenvold Avatar asked Aug 18 '09 19:08

krosenvold


People also ask

How can we inject beans in Spring?

The injection in Spring is either done via setter, field or constructor injection. Classes which are managed by Spring DI must conform to the Java bean standard. In the context of Spring classes are also referred to as beans or as spring beans.


1 Answers

My first thought is, are you sure the calls to spring are expensive? This stuff is pretty heavily optimized, so make sure it's actually a problem before trying to optimize it.

Assuming it is a problem, then an alternative is the exposeContextBeansAsAttributes and exposedContextBeanNames properties of InternalResourceViewResolver. You can use one or the other (but not both) to expose some or all of your beans as JSP attributes.

This raises the possibly of actually injecting Spring beans into your tag classes. For example, in your Spring context you can have:

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="exposeContextBeansAsAttributes" value="true"/>
</bean>

<bean id="myBean" class="com.x.MyClass"/>

Your JSP:

<MyTag thing="${myBean}"/>

SO if MyTag defines an attribute thing of type MyClass, the myBean spring bean should get injected as a normal JSP attribute.

like image 126
skaffman Avatar answered Sep 20 '22 19:09

skaffman