Caching in Spring Framework 3.1

    I may be mistaken, but it seems to me that the well-known Spring Framework has reached its peak by version 2.5 (when they introduced the active use of annotations), and as a matter of fact “polishing” goes on - even major release 3.0 is not much different from 2.5. The same can be said about the upcoming 3.1 - small improvements, chips - but nothing more. However, one “trick” in 3.1 seemed especially interesting to me - this is caching.

    In any application under development, we may at some point encounter a performance problem. One way to solve problems is through caching. Naturally, you can cache the data returned from the database (Hibernate - the most used in java does this anyway) - but much more interesting is the caching of the values ​​returned from the “services” level. The calculation of such values ​​can be quite time-consuming, including many calls to the database, other services, calculations - and accordingly caching at this level can lead to more significant results.
    In Spring Framework 3.1, this can be done using the @Cacheable annotation
    Actually, service level caching could be done in the Spring Framework before, just now it will become much easier.
    Value caching

    For example, if during profiling you found out that a certain method is “dumb”, for example (as in the documentation) the ISBN book return method: Now, in order to cache the values ​​returned by this method, it’s enough to add an annotation: This annotation itself hang up an interceptor, create a key according to the parameters, check if there is a value in the cache, if not, it will call the method and cache the result. And it's all? Almost, for completeness, you need:

    public Book findBook(ISBN isbn) {...}

    public Book findBook(ISBN isbn) {...}

    Set up caching in the application

    This is done in the application context xml configuration file: and configure the cache-manager - for example, the simplest (using ConcurrentMap) or ehcache (you can use other implementations):


    Clear cache

    Data must be cached carefully - it is always a potential source of errors when the data is updated, but there is no cache and the application uses outdated data. Clearing the cache can also be done using the annotation - @CacheEvict: That's all. Simply? It seems so. In fact, the caching mechanism is quite flexible, there are a number of additional features (such as writing your own annotations, generating keys, and much more. But the basic functionality looks so simple.

    @CacheEvict(value = "books", allEntries=true)
    public void loadBooks(InputStream batch)

    Also popular now: