- Cahce接口
package com.cy.pj.common.cache;
public interface Cache {
}
- DefaultCache类
package com.cy.common.cache;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.cy.pj.common.cache.Cache;
@Component
//@Lazy(false)
//@Lazy(true)
//@Scope("singleton")
@Scope("prototype")
public class DefaultCache implements Cache {
public DefaultCache() {
System.out.println("cache()");
}
@PostConstruct
public void init() {
System.out.println("init()");
}
@PreDestroy
public void destroy() {
System.out.println("destroy()");
}
}
- WeakCache类
package com.cy.pj.common.cache;
import org.springframework.stereotype.Component;
@Component
public class WeakCache implements Cache {
}
- SoftCache
package com.cy.pj.common.cache;
import org.springframework.stereotype.Component;
@Component("defaultCache1")
public class SoftCache implements Cache {
}
- 测试类
package com.cy.pj.common.cache;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class CacheTests {
@Autowired
@Qualifier("defaultCache")
private Cache cache01;
@Autowired
private Cache defaultCache1;
private Cache cache02;
@Autowired
public CacheTests(@Qualifier("weakCache") Cache cache02) {
this.cache02=cache02;
}
@Test
public void testCache01() {
System.out.println("cache="+cache01);
System.out.println("cache="+defaultCache1);
System.out.println("cache="+cache02);
}
}
- 运行结果