I'm using Spring and I would like to cache some data before starting my app.
I found some solutions in other posts to use @PostConstruct to call my @Service method (which are annotated @Cacheable), eg. How to load @Cache on startup in spring? I did that but when after application start I call REST endpoint which calls this service method again it's sending database request another time (so it's not cached yet). When I send request to endpoint for the second time data is cached.
Conclusion is that calling Service method on @PostConstruct didn't cause caching data from database.
Is it possible to cache data before starting app? How can I do that? Below is my code fragments.
@RestController
class MyController {
private static final Logger logger = LoggerFactory.getLogger(MyController.class);
@Autowired
MyService service;
@PostConstruct
void init() {
logger.debug("MyController @PostConstruct started");
MyObject o = service.myMethod("someString");
logger.debug("@PostConstruct: " + o);
}
@GetMapping(value = "api/{param}")
MyObject myEndpoint(@PathVariable String param) {
return service.myMethod(param);
}
}
@Service
@CacheConfig(cacheNames = "myCache")
class MyServiceImpl implements MyService {
@Autowired
MyDAO dao;
@Cacheable(key = "{ #param }")
@Override
public MyObject myMethod(String param) {
return dao.findByParam(param);
}
}
interface MyService {
MyObject myMethod(String param);
}
@Repository
interface MyDAO extends JpaRepository<MyObject, Long> {
MyObject findByParam(String param);
}
@SpringBootApplication
@EnableConfigurationProperties
@EnableCaching
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Primary
@Bean
public CacheManager jdkCacheManager() {
return new ConcurrentMapCacheManager("myCache");
}
}