【问题标题】:Execute Method on Spring start在 Spring 启动时执行方法
【发布时间】:2017-09-23 17:02:40
【问题描述】:

我想在应用程序启动期间(或更确切地说是在结束时)执行一些代码。我发现有几个资源使用@PostConstruct 注释、@EventListener(ContextRefreshedEvent.class)、实现 InitializingBean、实现 ApplicationListener...它们都在启动时执行我的代码,但应用程序属性的占位符并没有被替换片刻。因此,如果我的类有一个带有 @Value("${my.property}") 注释的成员,它会返回 "${my.property}" 而不是 yaml(或任何地方)中定义的实际值。 替换发生后如何执行我的代码?

【问题讨论】:

  • spring 配置将解析放置在@Value 中的属性占位符。如果它没有被加载,则意味着不正确的属性名称或特定的 yaml 未加载到上下文中。当然可以使用@PostConstuct来设置成员

标签: java spring spring-boot properties spring-config


【解决方案1】:

您可以实现InitializingBean,它有一个名为afterPropertiesSet() 的方法。该方法会在所有属性占位符被替换后调用。

【讨论】:

    【解决方案2】:

    @PostConstruct 在创建 bean 时调用。 Ypu 必须检查 spring 是否找到具有属性的文件。

    【讨论】:

      【解决方案3】:

      如果你有一个配置类,@Configuration,那么你可以尝试通过添加以下注释来显式导入你的属性文件:

      @PropertySource("classpath:your-properties-file.properties")
      

      任何其他非配置资源都应该在您的配置类之后加载,并且您的 @Value 注释应该可以正常工作。

      【讨论】:

        【解决方案4】:

        你应该像这样实现ApplicationListener<ContextRefreshedEvent>

        @Component
        public class SpringContextListener implements ApplicationListener<ContextRefreshedEvent> {
        
                @Value("${my.property}")
                private String someVal;
        
                /**
                 * // This logic will be executed after the application has loded
                 */
                public void onApplicationEvent(ContextRefreshedEvent event) {
                    // Some logic here
                }
            }
        

        【讨论】:

          【解决方案5】:

          spring boot 启动后即可获取。

          import org.springframework.beans.factory.annotation.Autowired;
          import org.springframework.beans.factory.annotation.Value;
          import org.springframework.boot.context.event.ApplicationReadyEvent;
          import org.springframework.context.ApplicationListener;
          import org.springframework.core.annotation.Order;
          import org.springframework.core.io.ResourceLoader;
          import org.springframework.stereotype.Component;
          
          @Component
          @Order(0)
          class ApplicationReadyInitializer implements ApplicationListener<ApplicationReadyEvent> {
          
              @Autowired
              ResourceLoader resourceLoader;
          
              @Value("${my.property}")
              private String someVal;
          
              @Override
              public void onApplicationEvent(ApplicationReadyEvent event) {
                  // App was started. Do something
              }
          
          }
          

          【讨论】:

            猜你喜欢
            • 2020-08-30
            • 2014-06-13
            • 1970-01-01
            • 1970-01-01
            • 2017-06-12
            • 2020-10-07
            • 1970-01-01
            • 2017-12-18
            • 1970-01-01
            相关资源
            最近更新 更多