This is my ProductServiceImpl class.
public class ProductServiceImpl implements ProductService {
@Autowired
GalaxyService gs ;
@PostConstruct
private void init() {
int hash = Objects.hash("Galaxy");
gs.updateByName(hash);
}
@Override
@Cacheable(value = "products", key = "T(java.util.Objects).hash(#p0)")
public String getByName(String name) {
System.out.println("Inside method");
slowLookupOperation();
return name + " : " + name;
}
@CacheEvict(value = "products", allEntries = true)
public void refreshAllProducts() {
//This method will remove all 'products' from cache, say as a result of flush API.
}
public void slowLookupOperation() {
try {
long time = 5000L;
Thread.sleep(time);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}}
Here is my GalaxyServiceImpl:
public class GalaxyServiceImpl implements GalaxyService {
@Override
@CachePut(value = "products", key = "#key")
public String updateByName(Integer key) {
return "Oh My Galaxy- " + key;
}}
From init() method of ProductServiceImpl, I was updating a cache element. Looks like it is Spring cache is not caching that method.
But, I do it from my Main class, it was caching the method. Main class in below:
public mainconstructor() {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
ProductService service = (ProductService) context.getBean("productService");
GalaxyService gs = (GalaxyService) context.getBean("galaxy");
int hash = Objects.hash("Galaxy");
gs.updateByName(hash);
System.out.println("Galaxy S8 ->" + service.getByName("Galaxy"));
((AbstractApplicationContext) context).close();
}
My application configuration class in below:
@EnableCaching
@Configuration
@ComponentScan(basePackages = {"com.websystique.spring", "com.samsung.gs8"})
public class AppConfig {
@Bean
public CacheManager cacheManager() {
return new EhCacheCacheManager(ehCacheCacheManager().getObject());
}
@Bean
public EhCacheManagerFactoryBean ehCacheCacheManager() {
EhCacheManagerFactoryBean factory = new EhCacheManagerFactoryBean();
factory.setConfigLocation(new ClassPathResource("ehcache.xml"));
factory.setShared(true);
factory.setAcceptExisting(false);
return factory;
}
@Bean
public GalaxyService galaxy() {
GalaxyService gs = new GalaxyServiceImpl();
return gs;
}}
Completes code available at- https://github.com/pijushcse/SpringCache
My question is what is the wrong from ProductServiceImpl, if I want to update a cache item? Why it works from Main why not from other class? TIA