Spring Spring MVCの起動完了後のソースコード解析


キーワード:spring容器のロードが完了したら一つのことをする(Contect RefreshedEventイベントを利用する)
应用シーン:多くの場合、私たちはある種類で終着時に何かをやりたいですが、spring管理対象を使って、他の種類を引用しました。だから、この種類を使って仕事をしていたら、カバンの空き針が間違っていました。これは初期化が完了した可能性があります。しかし、参照の他のクラスは必ずしも初期化が完了していないので、空のポインタエラーが発生しました。解決策は以下の通りです。
1、クラスがspringを継承するAppplication Listenerを書いて傍受し、Contect RefreshedEventイベントを監視する(初期化完了イベントが容易)
2、定義が簡単なbean:class=「comp.cear.potal.webservice.BeanDefineConfigle」または直接@Componeを使用します。
完全なクラスは以下の通りです。

package com.creatar.portal.webservice;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component("BeanDefineConfigue")
public class BeanDefineConfigue implements
ApplicationListener<ContextRefreshedEvent> {//ContextRefreshedEvent        ,spring          
// @Autowired
// private IRoleDao roleDao;
/**
*    ApplicationContext         
*/
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
// roleDao.getUserList();//spring                
System.out.println("spring       ================================================");
}
}
或いはxmlの構成方式(注釈ではない)を使って、簡単にビーンを配置すればいいです。

<bean id="beanDefineConfigue" class="com.creatar.portal.webservice.BeanDefineConfigue"></bean>
その他の定義方式は、完全なクラスは以下の通りです。

package com.creatar.portal.webservice;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component("BeanDefineConfigue2")
public class BeanDefineConfigue2 implements ApplicationListener<ApplicationEvent> {
List<String> list = new ArrayList<String>();
/**
*    ApplicationContext         
*/
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ContextRefreshedEvent) {
System.out.println("spring       ================================================888");
}
}
}
spring他のイベント:
もういくつかのイベントが含まれています。
Conttext Close Event   、Conttext RefreshedEvent  、Conttext StartEdent  、Conttext StopedEvent   、Request HandleEvent
後続の研究:
appicationtextとMVCを使った後のwebAppliationtextは上の方法を2回呼び出しますが、この2つの容器はどうやって区別しますか?
しかし、この時、webプロジェクトには二つの容器があります。一つはroot appication contextで、もう一つは私達自身のproject Name-servlet contextです。
この場合、onAppliation Event方法は2回実行されることになります。上記の問題を避けるために、root appication contextの初期化が完了したら、論理コードを呼び出します。他の容器の初期化が完了したら、何の処理もしません。修正後のコードは以下の通りです。

 @Override 
  public void onApplicationEvent(ContextRefreshedEvent event) { 
  if(event.getApplicationContext().getParent() == null){//root application context   parent,     . 
    //         , spring               。 
  } 
  } 
後の発見は以上の判断を加えても二回実行できます。加えないと三回、最終的な研究結果は以下の判断を使ってより正確です。event.getAppliation Context().get DisplayName().equals(「Root WebAppliation Cont」)
締め括りをつける
以上が本文のSprigMVCについてです。起動後、実行方法のソースコード解析の全部の内容は、皆さんの助けになりたいです。何か問題があったら、メッセージを残してください。ここでも皆さんの応援に感謝しています。