Spring's cached annotations

Source: Internet
Author: User

$

There are two ways for spring to support caching: annotations-driven cache XML declaration caching enable caching support

。 If we use Java configuration, then one of the configuration classes can be
Add @enablecaching on

Package com.lf;

Import org.springframework.cache.annotation.EnableCaching;
Import org.springframework.context.annotation.Configuration;

/**
 * Created by LF on 2017/5/8.
 */
@Configuration
@EnableCaching public
class Config {
}

XML-style

1, use @enablecaching to enable cache annotation support;
2, to achieve cachingconfigurer, and then inject the required CacheManager and keygenerator; starting from Spring4 the default keygenerator is Simplekeygenerator; Cacheable

@Cacheable can be marked on one method or on a class.

When marked on a method indicates that the method supports caching, and when marked on a class, it means that all methods of that class support caching.

For a method that supports caching, spring caches its return value after it is invoked to ensure that the next time the method is executed with the same parameters, the result can be obtained directly from the cache without the need to execute the method again.

Spring is caching the return value of a method with a key-value pair, and the value is the result of the method's return, and as for the key, Spring supports both the policy, the default policy, and the custom policy, which is described later.

It should be noted that caching is not triggered when a method that supports caching is invoked inside the object. @Cacheable can specify three properties, value, key, and condition. The Value property specifies the cache name

The Value property must be specified to indicate which cache the current method's return value is cached on, corresponding to the cache name. It can be a cache or multiple cache, which is an array when multiple cache needs to be specified.

  The @Cacheable ("Cache1")//cache is public
   User find (Integer ID) {return
      null

   ) that occurred on Cache1 The @Cacheable ({"Cache1", "Cache2"})//cache is the public
   User find (Integer ID) {return null, which occurs on cache1 and Cache2
   }
use key property to customize key

The key property is the key that is used to specify the return result of the spring cache method. This property supports Springel expressions. When we do not specify this attribute, spring uses the default policy to generate the key. Let's take a look at the customization strategy First, and the default policy will be introduced separately in the following text.

A custom policy means that we can specify our key by using the El Expression of spring. The EL expression here can use the method arguments and their corresponding properties. When using method parameters, we can use either "#参数名" or "#p参数index" directly. Here are a few examples that use parameters as key.

@Cacheable (value= "Users", key= "#id") public
   User find (Integer ID) {return
      null;
   }

   @Cacheable (value= "Users", key= "#p0") public
   User find (Integer ID) {return
      null;
   }

   @Cacheable (value= "Users", key= "#user. ID") Public
   user find (user user) {return
      null;
   }

   @Cacheable (value= "Users", key= "#p0. ID") Public
   User Find (user user) {return
      null;
   }

In addition to using the method parameters as key above, spring also provides us with a root object that can be used to generate key. The root object allows us to obtain the following information.

Property name Description Sample
MethodName Current method Name Root.methodname
Method Current method Root.method.name
Target The object that is currently being invoked Root.target
Targetclass Class of the object that is currently being invoked Root.targetclass
Args An array of current method parameters Root.args[0]
Caches The cache used by the currently invoked method Root.caches[0].name

We can also omit "#root" when we want to use the properties of the root object as a key, because spring uses the root object's properties by default. Such as:

@Cacheable (value={"users", "XXX"}, key= "Caches[1].name") public
   User Find (user user) {return
      null;
   }
The Condition property specifies the condition that occurs

Sometimes we may not want to cache a method for all the return results. This functionality can be achieved by condition properties. The Condition property defaults to NULL, indicating that all invocation cases will be cached. The value is specified by means of a springel expression, which, when true, is cached, and when false means no caching, that is, every time the method is called, the method executes once. The following example means caching only if the user ID is an even number

  @Cacheable (value={"Users"}, key= "#user. Id", condition= "#user. id%2==0") Public
   user find (user user) {
      System.out.println ("Find User by user" + user);
      return user;
   }
@CachePut

In an environment that supports spring cache, for a method that uses @cacheable annotations, spring checks the cache for the presence of the same key as a cached element in the cache before each execution, and then returns the result directly from the cache if it exists. Otherwise, the returned results are executed and stored in the specified cache. @CachePut can also declare a method to support caching. Unlike @cacheable, a method that uses the @cacheput annotation does not check the cache for the existence of a previously executed result before execution, but executes the method each time and stores the execution result as a key-value pair in the specified cache.

@CachePut can also be annotated on the class and on the method. The attributes we can specify when using @cacheput are the same as @cacheable.

The method is executed @CachePut ("users")/every time, and the result is stored in the specified cache public
   User find (Integer ID) {return
      null;
   }
@CacheEvict

@CacheEvict is used to annotate a method or class that needs to clear the cached element. When the token is on a class, it means that all of the methods in it execute will trigger the cached cleanup operation. @CacheEvict properties that can be specified are value, key, condition, allentries, and Beforeinvocation. The semantics of value, key, and condition are similar to those of @cacheable. That is, value indicates which cache the cleanup operation occurs on (the name of the cache); key indicates which key is to be cleared, and if unspecified, the default policy-generated key;condition is used to indicate the condition that the purge operation occurred. Let's take a look at the newly emerged two properties allentries and Beforeinvocation. Allentries Property

Allentries is a Boolean type that indicates whether all elements in the cache need to be purged. The default is False, which indicates that it is not required. When Allentries is specified as true, the Spring cache ignores the specified key. Sometimes we need a cache to erase all the elements, which is more efficient than a single purge element.

@CacheEvict (value= "users", allentries=true) public
   void Delete (Integer id) {
      System.out.println ("Delete user") By ID: "+ ID);
   }
Beforeinvocation Property

The purge action is triggered by default after the corresponding method succeeds, that is, the method does not trigger the cleanup operation if it fails to return successfully because of an exception being thrown. Use Beforeinvocation to change the time when the purge action is triggered, and when we specify that the property value is true, spring clears the specified element in the cache before calling the method.

@CacheEvict (value= "users", beforeinvocation=true) public
   void Delete (Integer id) {
      System.out.println (" Delete User by ID: "+ id";
   }

In addition to using @cacheevict to clear the cache element, when we use Ehcache as the implementation, we can also configure Ehcache's own elimination strategy, which is specified through the Ehcache configuration file. Since Ehcache is not the focus of this article, @Caching

@Caching annotations Allow us to specify multiple spring cache-related annotations on a method or class. It has three properties: cacheable, put, and evict, which are used to specify @cacheable, @CachePut, and @cacheevict respectively

@Caching (cacheable = @Cacheable ("Users"), evict = {@CacheEvict ("Cache2"),
         @CacheEvict (value = "Cache3", allentries = True)} public
   User find (Integer ID) {return
      null;
   }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.