简体   繁体   English

刷新 Spring 中的 bean 在 MySQL DB 中的表更新上启动应用程序

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

I have a bean in my spring boot application as follows:我的 spring 引导应用程序中有一个 bean,如下所示:

@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.在这里,我希望在我的 MySQL DB 中更新/删除/创建实体后,立即刷新带有 map 的上述 bean。

@Joy. @喜悦。 You can use a simple static attribute in your bean.您可以在 bean 中使用简单的 static 属性。

@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使用 DatabaseStudentLoader 有一个 static 参数


  @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");
      }
  
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM