|
| 1 | +package org.baeldung.caching.example; |
| 2 | + |
| 3 | +import org.springframework.beans.factory.annotation.Autowired; |
| 4 | +import org.springframework.cache.CacheManager; |
| 5 | +import org.springframework.cache.annotation.Cacheable; |
| 6 | +import org.springframework.context.ApplicationContext; |
| 7 | +import org.springframework.stereotype.Component; |
| 8 | + |
| 9 | +@Component |
| 10 | +@CacheConfig("addressDemo") |
| 11 | +public class CustomerDataService { |
| 12 | + |
| 13 | + @Autowired |
| 14 | + CacheManager cacheManager; |
| 15 | + |
| 16 | + /** |
| 17 | + * The method returns the customer's address, |
| 18 | + only it doesn't find it the cache- addresses and directory. |
| 19 | + * |
| 20 | + * @param customer the customer |
| 21 | + * @return the address |
| 22 | + */ |
| 23 | + @Cacheable("addresses", “directory”) |
| 24 | + public String getAddress1(Customer customer) { |
| 25 | + return customer.getAddress(); |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * The method returns the customer's address, |
| 30 | + but refreshes all the entries in the cache to load new ones. |
| 31 | + * |
| 32 | + * @param customer the customer |
| 33 | + * @return the address |
| 34 | + */ |
| 35 | + @CacheEvict(value="addresses", allEntries=true) |
| 36 | + public String getAddress2(Customer customer) { |
| 37 | + return customer.getAddress(); |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * The method returns the customer's address, |
| 42 | + but not before selectively evicting the cache as per specified paramters. |
| 43 | + * |
| 44 | + * @param customer the customer |
| 45 | + * @return the address |
| 46 | + */ |
| 47 | + @Caching(evict = { @CacheEvict("addresses"), @CacheEvict(value="directory", key="customer.name") }) |
| 48 | + public String getAddress3(Customer customer) { |
| 49 | + return customer.getAddress(); |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * The method uses the class level cache to look up for entries. |
| 54 | + * |
| 55 | + * @param customer the customer |
| 56 | + * @return the address |
| 57 | + */ |
| 58 | + @Cacheable // parameter not required as we have declared it using @CacheConfig |
| 59 | + public String getAddress4(Customer customer) { |
| 60 | + return customer.getAddress(); |
| 61 | + } |
| 62 | + |
| 63 | + /** |
| 64 | + * The method selectively caches the results that meet the predefined criteria. |
| 65 | + * |
| 66 | + * @param customer the customer |
| 67 | + * @return the address |
| 68 | + */ |
| 69 | + @CachePut(value="addresses", condition=”#customer.name=’Tom’”) |
| 70 | + @CachePut(value="addresses", unless=”#result.length>64”) |
| 71 | + public String getAddress5(Customer customer) { |
| 72 | + return customer.getAddress(); |
| 73 | + } |
| 74 | +} |
0 commit comments