Class Loading Application Context Spring

2019-05-06 14:41发布

问题:

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.

回答1:

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.



回答2:

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