2013-01-17 23 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

相关问题