4、Spring IOC拡張、Awareインターフェイスの深い理解
5、注釈の統合Spring Frameworkに基づいて、春のIOC拡張章の深い理解
6、Spring IOC拡張、Aopベースのカスタムアノテーションの深い理解
7、Spring IOC拡張、Springイベントとカスタムイベントの深い理解
prepareRefreshメソッドのrefreshメソッドの記事では、このメソッドは主にコンテナの状態を記録し、環境変数の検証を行うものですが、このメソッドのコードを見てみましょう:
protected void prepareRefresh() {
// 1. コンテナがリフレッシュを開始した時刻を記録する
this.startupDate = System.currentTimeMillis();
// 2. コンテナをアクティブにする
synchronized (this.activeMonitor) {
this.active = true;
}
if (logger.isInfoEnabled()) {
logger.info("Refreshing " + this);
}
// 3. ClassPathXmlApplicationContext空のメソッドを呼び出すと、スキップしてしまう。
initPropertySources();
// 4. StandardEnvironmentのvalidateRequiredPropertiesメソッドを呼び出す。
getEnvironment().validateRequiredProperties();
}
カスタムチェックサム環境変数のロジックはどうなっているのだろうかと疑問に思う人もいるだろうが、実際、私自身は、この役割はまだ非常に有用だと考えている。ここで環境変数はまだ多くの情報である、私はあなたの読者が気づいているかどうかわからない。
最初のケースでは、プロジェクトはSpringBootプロジェクトではなく、通常のSpringです:
設定クラス。
@Configuration
@ComponentScan("com.example.test")
public class Config {
}
校正を担当する豆
@Component
public class ConfigCheckBean implements EnvironmentAware {
private ConfigurableEnvironment environment;
@Override
public void setEnvironment(Environment environment) {
if (environment instanceof ConfigurableEnvironment){
ConfigurableEnvironment environment1 = (ConfigurableEnvironment)environment;
this.environment = environment1;
}
init();
this.environment.validateRequiredProperties();
}
private void init() {
this.environment.setRequiredProperties("aaa");
}
}
テストコード
public static void main(String[] args) {
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(Config.class);
}
キーaaaを持つ環境変数を追加していなかったので、この時点で開始するとエラーが報告されました:
@SpringBootApplication
@MapperScan(basePackages = {"com.example.studyspringbootdemo.mybatis.mapper"})
public class StudyspringbootdemoApplication {
public static void main(String[] args) {
// ApplicationContextの置き換えにSpringApplicationを指定し、SpringBootプロジェクトを起動する。
SpringApplication springBootApplication = new SpringApplication(StudyspringbootdemoApplication.class);
springBootApplication.setApplicationContextClass(MyApplicationContext.class);
springBootApplication.run();
}
// SpringBootがデフォルトで使用するAnnotationConfigServletWebServerApplicationContextを継承し、initPropertySourcesメソッドをオーバーライドする。
public static class MyApplicationContext extends AnnotationConfigServletWebServerApplicationContext{
@Override
protected void initPropertySources() {
// 親クラスのinitPropertySourcesは空ではないので、ロジックの正常な動作を維持するためには、親クラスのメソッドを呼び出す必要がある。
super.initPropertySources();
// aaa "チェックサムを追加する
getEnvironment().setRequiredProperties("aaa");
}
}
}
この場合も、対応する環境変数がないので起動に失敗します:



