java:aocache的单实例缓存(一)

上一篇博客《java:aocache:基于aspectJ实现的方法缓存工具》介绍了aocache的基本使用,

介绍@AoCacheable注解时说过,@AoCacheable可以定义在构造方法上,定义在构造方法,该构建方法就成了单实例模式。

也就是说,只要构建方法参数相同,new 返回的实例都是同一个,示例如下:

java 复制代码
	@Test
	public void test7Constructor() {
		try {
			Date d = new Date();
			TestUser user = new TestUser("jerry",0,d);
			log("user:{}",user);
			for(int i=0;i<5;++i) {
				TestUser o = new TestUser("jerry",0,d);
				log("u{}:{}",i,o);
                /** 每次 new 返回的都是同一个实例 */
				assertTrue(o == user);
			}
		} catch (Throwable e) {
			e.printStackTrace();
			fail(e.getMessage());
		}
	}
	private static class TestUser {
		String name;
		Integer age;
		Date birthdate;
		@AoCacheable
		TestUser() {
			this(null, null, null);
		}
		@AoCacheable
		protected TestUser(String name, Integer age, Date birthdate) {
			this.name = name;
			this.age = age;
			this.birthdate = birthdate;
		}
	}

注意

  • @AoCacheable定义在私有(private)构造方法上无效,因为基于AspectJ的工作原理,它不能拦截私有构造方法。
  • 对于是否将@AoCacheable定义在构造方法上要认真考虑是否适合你的使用场景,因为一旦定义了将@AoCacheable注解定义在构造方法上,该方法new操作就不能创建新实例。

所以@AoCacheable定义在构造方法的使用方式是有限制的。因为就无法再创建新实例,如果又希望保持构造方法创建新实例,又能得到单实例缓存。建议不要在构造方法上定义@AcCacheable注解注解,而是定义一个有@AcCacheable注解的静态方法用于获取单实例,示例如下:

java 复制代码
	protected TestUser(String name, Integer age, Date birthdate) {
		this.name = name;
		this.age = age;
		this.birthdate = birthdate;
	}
	@AcCacheable
	public static TestUser getSingleton(String name, Integer age, Date birthdate){
		new TestUser(name,age,birthdate);
	}

项目仓库

访问码云仓库获取完整代码及说明:
aocache: aocache(Aspect Oriented Cache)是一个基于aspectJ实现的方法缓存工具。 (gitee.com)

相关推荐
程序员黑豆6 小时前
Java字符串详解
java·前端·ai编程
EntyIU8 小时前
NFS离线部署
java
祈禾9 小时前
Redis三大缓存问题与分布式锁
运维·数据库·redis·笔记·分布式·缓存
OH_TPC11 小时前
HarmonyOS APP开发---“滤镜大师“图像处理App,需要用到这个库
java·图像处理·华为·harmonyos·鸿蒙
imaol112 小时前
链表 -- 环链表
java·前端·链表
imaol112 小时前
链表 -- 双向链表
java·前端·链表
2601_9638699513 小时前
【计算机毕业设计】基于Java的相框定制系统的设计与实现
java·开发语言·课程设计
xin_nai13 小时前
LeetCode热题100(Java)(7)链表(下)
java·leetcode·链表
于烛14 小时前
为什么hasNext() 对只有一个元素的集合返回 true?90%初学者都有的疑问
java
wuminyu14 小时前
JVM利用io_uring优化堆外内存性能原理剖析
java·linux·c语言·jvm·c++