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)

相关推荐
码农飞哥7 分钟前
互联网大厂Java求职面试实战:Spring Boot到微服务全景解析
java·spring boot·微服务·maven·hibernate·技术栈·面试技巧
IT成长史25 分钟前
deepseek梳理java高级开发工程师springboot面试题2
java·spring boot·后端
爱刘温柔的小猪39 分钟前
Redis+Caffeine构造多级缓存
redis·spring·缓存
hello1114-40 分钟前
Redis学习打卡-Day2-缓存更新策略、主动更新策略、缓存穿透、缓存雪崩、缓存击穿
java·redis·学习·缓存·javaweb
qq_266348731 小时前
springboot AOP中,通过解析SpEL 表达式动态获取参数值
java·spring boot·后端
极乐谷21 小时前
Maven 项目构建时编译错误问题排查与解决
java·maven
小Mie不吃饭1 小时前
【23种设计模式】分类结构有哪些?
java·设计模式·设计规范
bing_1581 小时前
MQTT 在Spring Boot 中的使用
java·spring boot·后端·mqtt
purpleseashell_Lili1 小时前
react 基本写法
java·服务器·前端
oneDay++2 小时前
# IntelliJ IDEA企业版高效配置指南:从主题到快捷键的终极优化
java·经验分享·intellij-idea·学习方法