【问题标题】:Refresh beans in a Spring Boot application on table update in MySQL DB在 MySQL DB 中的表更新上刷新 Spring Boot 应用程序中的 bean
【发布时间】:2021-08-30 22:24:35
【问题描述】:

我的 Spring Boot 应用程序中有一个 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
    ...
  }

}

在这里,我希望在我的 MySQL 数据库中更新/删除/创建实体后,立即刷新上述 bean。

【问题讨论】:

    标签: java mysql spring spring-boot


    【解决方案1】:

    @乔伊。 您可以在 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
      }
     
    
    

    使用 DatabaseStudentLoader 有一个静态参数

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-16
      • 2019-06-22
      • 2021-04-24
      • 1970-01-01
      相关资源
      最近更新 更多