Jon
Jon

Reputation: 3194

Implementing a singleton bean in Spring

I am trying to create a cache class for my website using Spring and have added the following code to my applicationContect.xml file:

<bean id="SiteCache" class="Cache.SiteCache">

What I am unsure of is how to initialize this class. Do I even need to initialize it myself or does Spring take care of that when the site loads? If so, how would I accept parameters within the constructor?

I would like the class to be used most of the time, as a quicker way of accessing variables to populate the site, but I need a way of checking if there is an instance in the first place, so that I can load an XML file from source otherwise.

What would be the best way to implement a cache in spring?

Many thanks,

Upvotes: 0

Views: 1719

Answers (3)

Jon
Jon

Reputation: 3194

It seemed all that was necessary was to load the XML file in the constructor of the cache class. I didn't even need to define a bean in the end, simply accepting it in my GET/POST methods for each controller was enough to keep the cache class a singleton. That way the XML file is only loaded once and saved into a cache object when the site gets built. After that the cache object can be used for easier access.

Thanks for the alternative suggestions though, they seem more effective on more complicated systems and it turned out mine didn't really need all that. I also had a rough idea and only needed a bit of reminding!

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

What I am unsure of is how to initialize this class.

By default (providing your definition) Spring will create exactly one instance of bean and use it everywhere where other code requires it.

how would I accept parameters within the constructor?

Check out 4.4.1.1 Constructor-based dependency injection:

<bean id="foo" class="x.y.Foo">
  <constructor-arg ref="bar"/>
  <constructor-arg value="42"/>
</bean>

and 4.4.2.7 XML shortcut with the c-namespace:

<bean id="foo" class="x.y.Foo" c:_0-ref="bar" c:_1-ref="baz">

What would be the best way to implement a cache in spring?

Using built-in Spring cache abstraction is a good start.

Upvotes: 5

Alex Barnes
Alex Barnes

Reputation: 7218

What would be the best way to implement a cache in spring?

In terms of implementing a cache, I would recommend using an existing Cache implementation such as EhCache or similar in conjunction with the Spring cache abstraction.

This makes caching as simple as annotating a method which should access the cache with @Cacheable. Spring will attempt to use the cache before executing the method.

Whilst it might seem simple to write your own cache the hardest part is always the cache invalidation.

Upvotes: 0

Related Questions