Creating custom caching annotations

Spring's cache abstraction allows you to create custom caching annotations for your application to recognize the cache method for the cache population or cache eviction. Spring's @Cacheable and @CacheEvict annotations are used as Meta annotations to create custom cache annotation. Let's see the following code for custom annotations in an application:

    @Retention(RetentionPolicy.RUNTIME) 
    @Target({ElementType.METHOD}) 
    @Cacheable(value="accountCache", key="#account.id") 
    public @interface SlowService { 
    } 

In the preceding code snippet, we have defined a custom annotation named as SlowService, which is annotated with Spring's @Cacheable annotation. If we use @Cacheable in the application, then we have to configure it as the following code:

    @Cacheable(value="accountCache", key="#account.id") 
    public Account findAccount(Long accountId) 

Let's replace the preceding configuration with our defined custom annotation, with the following code:

    @SlowService 
    public Account findAccount(Long accountId) 

As you can see, we use only the @SlowService annotation to make a method cacheable in the application.

Now let's move on to the next section, where we'll see which are the best practices we should consider at the time of cache implementation in anapplication.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset