4

I have a Spring web project and I need load some classes after application context has been initialized because those classes will eventually used in future. Thus, I try to preload them before use to improve performance.

How to do it ?

Please help.

Thanks.

4
  • Anyone please help. Thanks. Commented Jan 31, 2013 at 7:10
  • ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); GenericDAOImpl dao = (GenericDAOImpl) ctx.getBean("genericDaoImpl"); ClassLoader clsLoader = Thread.currentThread().getContextClassLoader(); clsLoader.loadClass(arg0); Is it this one or there is better approach ? Commented Jan 31, 2013 at 7:23
  • Kindly provide some answer. Commented Feb 5, 2013 at 8:53
  • You comment might have added to the confusion. Do you want to pre-load beans ? Load all your beans using your applicationContext definition -The default behavior for ApplicationContext implementations is to eagerly pre-instantiate all singleton beans at startup. Commented Feb 11, 2013 at 16:35

2 Answers 2

2

To load a class into JVM it is enough simply to call Class.forName('com.foo.bar.MyClassToPreLoad') method. You can do it e.g. in your own implementation of javax.servlet.ServletContextListener and then register it in web.xml

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

Or you can do it in any of your Spring beans implementing org.springframework.beans.factory.InitializingBean interface. Or if you don't want to implement interface you can do it in any bean method without arguments and register it as a init-method for this bean:

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

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

Or http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-postconstruct-and-predestroy-annotations if you prefer annotation based configuration.

Hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

1

I think u have not mentioned the scope of yours bean.If you have not mentioned the scope in application context then default container use singleton scope.It means the same instance of bean is used throughout urs system unless you close the container .The instances of bean remain is always the same.If you want to overwrite the default behaviour use can provide scope for beans in urs applicationcontext.You better see in this link i have once ask question about same problem. Pre-loading and lazy loading in spring with tomcat

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.