2017-01-30 8 views
0

私はアプリケーションの起動時に静的共有メモリ構造から読み込むいくつかのBeanを初期化しようとしています。以前は@PostContructを使用していましたが、Spring AOPの機能(Config、Resourcesなど)を利用して繰り返しを避けるため、イベントベースの初期化に移行したいと考えています。Springアプリケーションの初期化

すべてのデータBeanは、このインターフェイスを実装:

public interface DataInterface { 
    public void loadData(); 

    public List<String> getResults(String input); 
} 

を私は両方のServletContextListenerWebApplicationInitializerインタフェースを実装しようとしたが、呼ばれ得るように見えることでもないです。

@Service 
public class AppInit implements WebApplicationInitializer { 
    @Autowired 
    DataInterface[] dataInterfaces; 

    @Override 
    public void onStartup(ServletContext servletContext) throws ServletException { 
     // This does not get called 
     for (DataInterface interface : dataInterfaces) 
      interface.loadData(); 
    } 
} 


@WebListener 
public class AppContextListener implements ServletContextListener { 
    @Override 
    public void contextInitialized(ServletContextEvent servletContextEvent) { 
     // does not get called 
    } 

    @Override 
    public void contextDestroyed(ServletContextEvent servletContextEvent) { 
     // does not get called 
    } 
} 

また、私はSpringApplicationを開始した後に返すmain()関数の最後に、これらのクラスを初期化しようとすることができます。

@SpringBootApplication 
public class Application { 
    public static void main(String[] args) { 
     SpringApplication.run(Application.class, args); 
     // Can I initialize the DataInterfaces here??? 
    } 
} 

より良い方法があるようです。

編集:私は、私はSpring docsに記載されているContext*イベントのいずれかを受け取ることができませんでしたので、下記の溶液を使用して終了

@Component 
public class DalInitializer implements ApplicationListener { 
    @Autowired 
    DataInterface[] dataInterfaces; 

    @Override 
    public void onApplicationEvent(ApplicationEvent applicationEvent) { 
     if (applicationEvent.getClass() == ApplicationReadyEvent.class) { 
      for (DataInterface interface : dataInterfaces) 
       interface.loadData(); 
     } 
    } 
} 

答えて

1

使用Springアプリケーションのイベントリスナーは、予想または文書化されているように、この実際に動作しますが、Better application events in Spring Framework

+0

を参照してください。私はグローバルなApplicationListenerを実装して、どのようなイベントを確認し、 'ApplicationReadyEvent'で解決しました。私は[Springのドキュメント]にリストされている 'Context *'イベントを見ていませんでした(http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#context-機能性イベント)。 – saarp

関連する問題