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)

相关推荐
南汐以墨1 分钟前
一个另类的数据库-Redis
数据库·redis·缓存
计算机毕设指导622 分钟前
基于SpringBoot校园学生健康监测管理系统【源码文末联系】
java·spring boot·后端·spring·tomcat·maven·intellij-idea
mysuking27 分钟前
springboot与springcloud对应版本
java·spring boot·spring cloud
希望永不加班28 分钟前
SpringBoot 数据库连接池配置(HikariCP)最佳实践
java·数据库·spring boot·后端·spring
迈巴赫车主31 分钟前
蓝桥杯3500阶乘求和java
java·开发语言·数据结构·职场和发展·蓝桥杯
身如柳絮随风扬1 小时前
Lambda、方法引用与Stream流完全指南
java·开发语言
yaoyouzhong1 小时前
基于SpringBoot和PostGIS的云南与缅甸的千里边境线实战
java·spring boot·spring
姗姗的鱼尾喵2 小时前
Spring/SpringBoot 面试高频(含IOC/AOP/事务)
java·spring boot·面试
Mr_Xuhhh2 小时前
从理论到实践:深入理解算法的时间与空间复杂度
java·开发语言·算法
一个有温度的技术博主2 小时前
Redis AOF持久化:用“记账”的方式守护数据安全
redis·分布式·缓存