13

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

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

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

这段代码运行良好,但有一个不受欢迎的缺点,即我花了大约一半的页面渲染时间来查找 spring bean,因为每次调用标签时都会发生这种情况。我在想也许将 bean 放入应用程序范围或至少会话范围。但真正处理这个问题的最聪明的方法是什么?

4

3 回答 3

11

我的第一个想法是,你确定调用 spring 很贵吗?这些东西已经过大量优化,所以在尝试优化它之前确保它确实是一个问题。

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

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

<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定义了一个thingtype的属性MyClassmyBeanspring bean 应该作为一个普通的 JSP 属性被注入。

于 2009-08-18T21:11:49.810 回答
8

一种更简单的方法是在标签类上使用 @Configurable 注释,这将使 Spring 在标签初始化时自动连接依赖项。然后可以使用@AutoWired 注释标记任何所需的依赖项,即使该标记未在 Spring 容器中初始化,Spring 也会连接到依赖项中。

于 2010-10-22T00:44:12.357 回答
5

实现此目的的另一种方法是使用静态属性来保存依赖项。就像下面这样:

public class InjectedTag extends SimpleTagSupport {
//In order to hold the injected service, we have to declare it as static
    private static AService _service;   
/***/   
@Override   
public void doTag() throws IOException {    
          getJspContext().getOut().
          write("Service injected: " + _service + "<br />");    
}   
public void setService(AService service) { 
        _service = service;     
} 
}

在您的应用程序上下文中,您必须同时注册两者,以便 JSP 标记有机会被 Spring 启动。我们用魔法去...

<bean id="aService" class="com.foo.AService">
  <!-- configure the service. -->
</bean>
<bean class="com.foo.InjectedTag" >
  <property name="service"><ref local="aService"/></property>
</bean>

很酷,现在我们的 JSP 标签中可以看到 aService 了 :)

于 2011-04-08T07:48:42.480 回答