Loading images only one time per spring webapp
I need to load a bunch of images into my Spring webapp. For performance reasons this should only be done after starting the webapp. The images should be saved in a开发者_运维问答 singleton to access from multiple users, sessions etc
I already build a Java Bean with an initalizer that loads the images, in my controller I inject this bean and get the images. Works, but injecting isn't the right thing for this.
How can I build a singleton bean to hold the images and only load the images one time per webapp?
Have you considered using EhCache built-in web caching? Just add it to your web.xml
:
<filter>
<filter-name>pageCachingFilter</filter-name>
<filter-class>net.sf.ehcache.constructs.web.filter.SimpleCachingHeadersPageCachingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>pageCachingFilter</filter-name>
<url-pattern>*.htm</url-pattern>
<url-pattern>*.js</url-pattern>
<url-pattern>*.png</url-pattern>
<url-pattern>*.gif</url-pattern>
<url-pattern>*.jpg</url-pattern>
<url-pattern>*.css</url-pattern>
</filter-mapping>
And configure SimplePageCachingFilter
cache in your ehcache.xml
:
<cache name="SimplePageCachingFilter"
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="31536000"
timeToLiveSeconds="31536000"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"
statistics="true"
/>
EhCache will now intercept all client-side requests for static resources, read them once, put them in cache and return to the user. To make it even better, it will even add HTTP Expiry
headeres so the client won't call you again for the same resource.
Isn't this approach better compared to manually-written loading and caching in a singleton?
精彩评论