2013-01-17 25 views
4

我有一個Spring Web項目,我需要在應用程序上下文初始化後加載一些類,因爲這些類將來最終會使用。因此,我嘗試在使用前預加載它們以提高性能。類加載應用程序上下文彈出

怎麼辦?

請幫忙。

謝謝。

+0

任何人都請幫忙。謝謝。 – peterwkc

+0

ApplicationContext ctx = new ClassPathXmlApplicationContext(「classpath:applicationContext.xml」); GenericDAOImpl dao =(GenericDAOImpl)ctx.getBean(「genericDaoImpl」); ClassLoader clsLoader = Thread.currentThread()。getContextClassLoader(); clsLoader.loadClass(arg0);這是一個還是有更好的方法? – peterwkc

+0

請提供一些答案。 – peterwkc

回答

2

要將類加載到JVM中,只需調用Class.forName('com.foo.bar.MyClassToPreLoad')方法即可。 你可以做到這一點,例如在自己實現javax.servlet.ServletContextListener,然後註冊它在web.xml

<listener> 
    <listener-class>com.foo.bar.MyClassPreloadingContextListener</listener-class> 
</listener> 

或者你可以在任何執行org.springframework.beans.factory.InitializingBean接口你的Spring beans的做到這一點。或者,如果你不想實現接口,你可以做任何bean方法不帶任何參數,並將其註冊爲初始化方法此Bean:

<bean class="com.foo.bar.MyClassPreloadingBean" init-method="preloadClasses"/> 

詳見http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-lifecycle-initializingbean

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-postconstruct-and-predestroy-annotations如果您更喜歡基於註釋的配置。

希望它有幫助。

1

我想你還沒有提到你的bean的範圍。如果你沒有在應用上下文中提到範圍,那麼默認容器使用singleton scope.It意味着在整個urs系統中使用相同的bean實例,除非關閉容器。bean的實例保持不變。如果你想覆蓋默認行爲,可以在urs applicationcontext中爲bean提供範圍。你最好在這個鏈接中看到我曾經問過同樣的問題。 Pre-loading and lazy loading in spring with tomcat

相關問題