2012-07-12 142 views
0

我在我的Spring應用上下文文件中定義了UserCredetnialsDatSourceAdapter。我也有一個通過DelegatingFilterProxy添加到Spring的自定義過濾器。Spring MVC:使用@Autowire獲取對不同spring bean實例的引用

此過濾器使用@Autowire來獲取對DataSource Bean的引用。我也@Autowire DAO中的數據源。當我調試時,我在Filter和DAO實例中看到了不同的實例ID到數據源。爲什麼默認情況下有2個單例是單實例?

我也解僱了jvisualvm,我看着堆和我的應用程序中的所有我的bean有2個實例?感謝任何見解,也許豆前/後處理有一些事情做,或者我不應該在過濾器中使用@Autowire。任何幫助apprciated。謝謝!

編輯

<context-param> 
<param-name>contextConfigLocation</param-name> 
<param-value>/WEB-INF/config-context.xml</param-value> 
</context-param> 

<servlet> 
    <servlet-name>springmvc</servlet-name> 
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <load-on-startup>1</load-on-startup> 
</servlet> 

<servlet-mapping> 
    <servlet-name>springmvc</servlet-name> 
    <url-pattern>*.html</url-pattern> 
</servlet-mapping> 

<init-param> 
<param-name>contextConfigLocation</param-name> 
    <param-value>/WEB-INF/web-context.xml,/WEB-INF/config-context.xml</param-value> 
</init-param> 

有趣,我想我明白了怎麼回事。有2個實例,因爲有2個上下文。一個爲應用程序和1爲每個請求(線程)我假設?有沒有一種方法可以指定使用哪種上下文?也許過濾器不是答案,我需要使用AOP。需要研究如何在@Aspect中注入一個bean,如果這是可能的話。

謝謝!

-Joe

+2

你可以發佈你的web.xml文件嗎?檢查您是否沒有構建使用相同配置文件的兩個不同的應用程序上下文。 – Luciano 2012-07-12 18:11:57

+1

您的應用程序上下文是否實例化了兩次,一次是通過web.xml並且一次是在代碼中? – GriffeyDog 2012-07-12 18:15:39

回答

2

您導入您的/WEB-INF/config-context.xml作爲根應用程序上下文(一個由ContextLoaderListener裝起來),以及您的網絡環境(由DispatcherServlet加載)的一部分。您可以將其從DispatcherServlet中刪除。

+0

感謝Luciano和GriffyDog的快速反應,使我得到了答案,並向Biju提供瞭解釋。 – user943583 2012-07-12 19:26:08