1

In spring boot, I want to take data from database and store it into a bean object. This needs to be done once (cache), and for further request bean object needs to be used, not to make database call again.

Example

/*
"DataFromDB" -> bean should have the values
*/

List<Users> uList = ApplicationContext.getBean("DataFromDB");

Is there any way to achieve this ?

Thank you

  • You can check this one: https://stackoverflow.com/questions/43575123/is-there-a-way-to-store-java-variable-object-in-application-context-without-xml – 0xh3xa Jun 13 '21 at 11:21

3 Answers3

2

During your application boot, you can simply create a bean List<Users> uList and populate it with your required info.

Bean creation will happen once and whenever you want to reuse it, just get that bean. Spring will take care of the rest.

Somewhere in a config file, declare the bean:

@Component
public class InitialConfiguration {

    @Bean
    public List<Users> ulist() {
        List<Users> uList = null;
        // ulist = populate it from db
        return uList;
    }
}

Spring will create a ulist bean and store it. Now whenever you want to use it, you can simply autowire it into your variables:

@Service
public class SomeRandomClass {
    @Autowire
    List<Users> ulist;
    
    public void performOperationOnUList() {
        ulist.get(0); // use it
    }
}
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
0

you can use a caching mechanism like ehcache

To add Ehcache to your application, here is the very basic approach you can follow.

  1. Add Ehcache through your build tool. Here is an example for Gradle.

    dependencies {
        compile("org.hibernate:hibernate-ehcache:5.2.12.Final")
    }
    
  2. Add Ehcache configuration, Here I'm using annotation-based bean configuration.

     @Configuration
     @EnableCaching
     public class CacheConfiguration {
    
         @Bean
         public EhCacheManagerFactoryBean ehCacheManagerFactory() {
             EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean();
             cacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
             cacheManagerFactoryBean.setShared(true);
    
             return cacheManagerFactoryBean;
         }
    
         @Bean
         public EhCacheCacheManager ehCacheCacheManager() {
             EhCacheCacheManager cacheManager = new EhCacheCacheManager();
             cacheManager.setCacheManager(ehCacheManagerFactory().getObject());
             cacheManager.setTransactionAware(true);
    
         return cacheManager;
         }
     }
    
  3. Define cache Regions. Here you can define individual caches for each repository you want to cache. create file named ehcache.xml and place in classpath.

     <?xml version="1.0" encoding="UTF-8"?>
     <!DOCTYPE ehcache>
     <ehcache>
     <diskStore path="java.io.tmpdir"/>
    
         <cache name="usercache" maxElementsInMemory="100" eternal="false" timeToIdleSeconds="600" timeToLiveSeconds="3600" overflowToDisk="true"/>
     </ehcache>
    
  4. Add Cachable annotation to transactional methods where you want to cache the DB operation.

     @Cacheable(value = "userCache", key = "#p0")
     public Company find(Long id) {
         //db operation in here
     }
    
ThilankaD
  • 1,021
  • 1
  • 13
  • 24
-1

From your problem statement, what I can understand is you want to cache objects from database, caching should be done only once (preferably on application start-up) and should be accessible anywhere in the context.

For this, you can store the data from db in a static final collection. The caching operation can be done on application startup via EventListener annotation.

    @Component
public class DbCache {

    public static final List<Object> dbCache = new ArrayList<>();

    @EventListener(value = ApplicationReadyEvent.class)
    private void initCache() {

        List<Object> dataFromDB = // data fetched from DB

        dbCache.addAll(dataFromDB);
    }

    public static List<Object> getDbCache() {
        return dbCache;
    }
}

You can use the DbCache.getDbCache() anywhere in your code now to fetch the data.

itsSKP
  • 104
  • 5