Refresh beans in a Spring Boot application on table update in MySQL DB

Viewed 188

I have a bean in my spring boot application as follows:

@Component
public class DatabaseStudentLoader {

  private final StudentRepository studentRepository;
  private final Map<String, Student>> idToStudentEntityMap;

  /**
   * Instantiates a new Database loader.
   *
   * @param studentRepository the student repository
   */
  public DatabaseStudentLoader(StudentRepository studentRepository) {
    this.studentRepository = studentRepository;
  }

  public void doSomeOperation() {

     //here I am constructing the map, reading entities from DB
    ...
  }

}

Here, I would like the above bean with the map to be refreshed as soon as an entity gets updated/deleted/created in my MySQL DB.

1 Answers

@Joy. You can use a simple static attribute in your bean.

@Component
public class DatabaseStudentLoader {

    // this a static var
    private static Map<String, Student>> idToStudentEntityMap;

    @Value("${some-value-from-spring-if-you-need}")
    private String someValueFromSpringIFYouNeed;

    @PostConstruct
    public void init(){
        // instance map using safely operations
        idToStudentEntityMap = new ConcurrentHashMap<String, Student>();
    }
    
    public void addStudentIntoContext(String key, Student student) {
        // check some roles, if already exists or other logic as you need
        idToStudentEntityMap.put(key, student );
    }
        
    public Student getStudentFromContext(String key) {
        // check some roles, if already exists or other logic as you need
        idToStudentEntityMap.get(key);
    }
    
    // .... all methods about this class
  }
 

using DatabaseStudentLoader has an static parameter


  @Service
  public class ServiceUsingDataBase{
  
      @Autowired
      private DatabaseStudentLoader databaseStudentLoader;
      
      public setValueExample(){
        // adding student into static map context that can be used in all application in any time even in updated/deleted/created in my MySQL DB
        databaseStudentLoader.addStudentIntoContext("key", new Student());
      }
      
      public getValueExample(){
        // read student from static map context that can be used in all application in any time
        Student student = databaseStudentLoader.getStudentFromContext("key");
      }
  
  }

Related