如何将 spring bean 注入 jsp 2.0 SimpleTag? [英] How to inject spring beans into a jsp 2.0 SimpleTag?

查看:26
本文介绍了如何将 spring bean 注入 jsp 2.0 SimpleTag?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我需要spring bean的jsp 2.0标签使用这个代码:

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

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

我刚得到第一个匹配的 bean.

The I just get the first matching bean.

这段代码工作正常,但有一个不受欢迎的缺点,我花了大约一半的页面渲染时间来查找 spring bean,因为每次调用标记时都会发生这种情况.我在想也许将 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 ?

推荐答案

我的第一个想法是,你确定调用 spring 很昂贵吗?这些东西经过了大量优化,因此在尝试优化之前请确保它确实存在问题.

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.

假设它一个问题,那么另一种选择是InternalResourceViewResolverexposeContextBeansAsAttributesexposedContextBeanNames属性.您可以使用其中一个(但不能同时使用)将部分或全部 bean 公开为 JSP 属性.

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.

这增加了将 Spring bean 实际注入标签类的可能性.例如,在您的 Spring 上下文中,您可以:

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"/>

您的 JSP:

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

所以如果 MyTag 定义了 MyClass 类型的属性 thingmyBean spring bean 应该被注入为一个普通的 JSP 属性.

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

这篇关于如何将 spring bean 注入 jsp 2.0 SimpleTag?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆