簡體   English   中英

如何將spring beans注入jsp 2.0 SimpleTag?

[英]How to inject spring beans into a jsp 2.0 SimpleTag?

目前我需要spring bean的jsp 2.0標簽使用此代碼:

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

我剛剛得到第一個匹配的bean。

這段代碼運行正常,但是有一個不希望出現的缺點,我花了大約一半的頁面渲染時間來查找spring bean,因為每次調用一個標簽時都會發生這種情況。 我想也許可以將bean放入應用程序范圍或至少是會話范圍。 但是,處理這個問題的最聰明方法是什么?

我的第一個想法是,你確定春天的電話很貴嗎? 這些東西經過了大量優化,因此在嘗試優化之前確保它確實是一個問題。

假設這一個問題,那么替代方案是InternalResourceViewResolverexposeContextBeansAsAttributesexposedContextBeanNames屬性。 您可以使用其中一個(但不是兩個)將一些或所有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定義屬性thing類型MyClass ,在myBean的Spring bean應該得到注入作為一個正常的JSP屬性。

一種更簡單的方法是在標記類上使用@Configurable注釋,這將使Spring在標記初始化時自動連接依賴項。 然后可以使用@AutoWired批注標記任何所需的依賴項,即使標記未在Spring容器中初始化,Spring也會依賴於依賴關系。

實現此目的的另一種方法是使用靜態屬性來保存依賴項。 如下所示:

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;     
} 
}

在您的applicationcontext中,您必須注冊兩者,以便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標簽中可以看到一個服務:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM