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)

相关推荐
用户3521802454754 小时前
当 Prompt 学会"热更新":Spring Boot × Nacos3 AI 实战
java·spring boot·ai编程
东坡白菜7 小时前
破局全栈:一个前端开发的Java入门实战记录(1)
java·全栈
唐青枫7 小时前
Java Tomcat 实战指南:从 Servlet 容器到 Spring Boot 部署
java
wsaaaqqq8 小时前
roudan:自由选择实体、灵活操作数据、快速写入数据库的 Java 框架
java
plainGeekDev11 小时前
null 判断 → Kotlin 可空类型
android·java·kotlin
糖拌西瓜皮11 小时前
Java开发者视角:深入理解Node.js异步编程模型
java·后端·node.js
plainGeekDev11 小时前
getter/setter → Kotlin 属性
android·java·kotlin
一线大码11 小时前
Smart-Doc 的简单使用
java·后端·restful
MacroZheng13 小时前
Claude Code官方桌面端正式发布,夯爆了!
java·人工智能·后端