2009-08-18 71 views
13

目前我需要Spring bean的JSP 2.0標籤使用此代碼:如何將spring bean注入到jsp 2.0 SimpleTag中?

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

的我只是得到第一個匹配的bean。

此代碼工作正常,但不想要的缺點,我花了大約一半我的網頁渲染時間查找春豆,因爲這發生的每一個標籤調用時。我在想也許把bean放到應用程序範圍或至少會話範圍內。但是,處理這個問題最聰明的方法是什麼?

+0

「[http://stackoverflow.com/questions/3445908/is-there-一個優雅的方式注入一個彈簧管理的bean到一個java自定義簡單] [1]'有一個很好的答案。 [1]:http://stackoverflow.com/questions/3445908/is-there-an-elegant-way-to-inject-a-spring-managed-bean-into-a-java- custom-simpl – Angus 2012-03-02 20:01:48

回答

11

我首先想到的是,你一定要春呼叫貴嗎?這些東西是非常優化的,所以在試圖優化它之前確保它確實是一個問題。

假設它是問題,那麼可替換的是在InternalResourceViewResolverexposeContextBeansAsAttributesexposedContextBeanNames性質。您可以使用其中一個(但不能同時使用)將部分或全部bean公開爲JSP屬性。

這就提出了一個可能的實際Spring Beans注入到你的標籤類。例如,在你的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定義MyClass類型的屬性thing,在myBean的Spring bean應該得到注入作爲一個正常的JSP屬性。

+0

是的,它們相對較貴。特別是因爲標籤被用於循環。我們使用60-70%的執行時間來討論上述邏輯的1-200次調用。其餘的代碼是乾淨優雅的。 – krosenvold 2009-08-19 04:25:12

8

一個更簡單的方法是在你的標籤類中使用@Configurable註解,這將使Spring自動連線當標籤被初始化的依賴關係。任何必需的依賴關係都可以使用@AutoWired標註進行標記,並且即使標籤未在Spring容器中初始化,Spring也會在依賴項中進行連接。

+0

您可以擴展嗎?謝謝 – 2015-08-19 08:58:03

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

在你的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> 

很酷吧,現在aService可見在我們的JSP標籤:)