我们知道缓存对于提高系统的性能有着非常重要的影响,spring在3.*的版本之后集成了cache技术,并且是基于annotation的实现,使用起来还是非常方便的。这里只是对spring cache做一个简单的了解。
业务层实现如下:
@Service
public class BookService {
@Resource
private BookMapper bookMapper;
@Cacheable(value="books")
public List<Book> listBooks(){
return this.bookMapper.findAll();
}
}
如图所示:方法上添加:@Cacheable(value="books")
application.xml
<cache:annotation-driven/>
<bean class="org.springframework.cache.support.SimpleCacheManager" id="cacheManager">
<property name="caches">
<set>
<bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
p:name="books"/>
</set>
</property>
</bean>
测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/beans.xml")
public class MyTest {
@Resource
private BookService bookService;
@Test
public void test() {
System.out.println("---------------------");
List<Book> list= this.bookService.listBooks();
for(Book book : list) {
System.out.println(book);
}
System.out.println("========================");
List<Book> list1= this.bookService.listBooks();
for(Book book : list1) {
System.out.println(book);
}
}
}
输出结果:
从输出我们可以看出,第一次会创建seesion并查询数据库,而第二次直接输出!!